Imugi Imugi - 8 months ago 63
C# Question

Split array in array of array with LINQ

I would like to split my array that consists of objects in arrays, grouping them by some property of the type (let's say

string Group {get; set;}


At the beginning I have

IEnumerable<T> array.

Then I would like to get

IEnumerable<IEnumerable<T>> array.

Of course, I can do it without LINQ, but it will look too ugly and verbose.

Answer Source
array.GroupBy(item => item.Group)

this will give you IEnumerable<IGrouping<string, YourType>>. The IGrouping<string, YourType> extends IEnumerble<YourType> with Key, which will be the value of Group property in your example:

foreach (var g in array.GroupBy(item => item.Group))
    Console.WriteLine("Group='{0}', {1} items", g.Key, g.Count());