Posts

Showing posts with the label Linq

Concat All Strings Inside A List Using LINQ

Answer : String.Join(delimiter, list); is sufficient. By using LINQ, this should work; string delimiter = ","; List<string> items = new List<string>() { "foo", "boo", "john", "doe" }; Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j)); class description: public class Foo { public string Boo { get; set; } } Usage: class Program { static void Main(string[] args) { string delimiter = ","; List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" }, new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } }; Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo); Console.ReadKey(); } } And here is my best :) items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j) This is for a string array: string.Join(delimiter, array)...

Can LINQ Be Used In PowerShell?

Answer : The problem with your code is that PowerShell cannot decide to which specific delegate type the ScriptBlock instance ( { ... } ) should be cast. So it isn't able to choose a type-concrete delegate instantiation for the generic 2nd parameter of the Where method. And it also does't have syntax to specify a generic parameter explicitly. To resolve this problem, you need to cast the ScriptBlock instance to the right delegate type yourself: $data = 0..10 [System.Linq.Enumerable]::Where($data, [Func[object,bool]]{ param($x) $x -gt 5 }) Why does [Func[object, bool]] work, but [Func[int, bool]] does not? Because your $data is [object[]] , not [int[]] , given that PowerShell creates [object[]] arrays by default; you can, however, construct [int[]] instances explicitly: $intdata = [int[]]$data [System.Linq.Enumerable]::Where($intdata, [Func[int,bool]]{ param($x) $x -gt 5 }) To complement PetSerAl's helpful answer with a broader answer to match the qu...