tags:

views:

63

answers:

2

I have a List that I need to split into sublists, one for each value of MyStruct.GroupingString. Can I do this via linq?

+2  A: 
List<List<StructType>> groupings = list.GroupBy(x => x.GroupingString)
                                       .Select(x => x.ToList()).ToList();
Mehrdad Afshari
ouch!!!!!!!!!!!!!! :)
leppie
@leppie: why? Isn't this what the OP says he wants? :-?
Mehrdad Afshari
I'd probably skip the entire second line (keep it as an IEnumerable of IGroupings), but this IS specifically what he asked for. :)
Sapph
@Mehrdad Afshari: It is correct, but `ToLookup` just does it so much nicer :) OTOH, yours will generate more efficient Linq2SQL. :)
leppie
+2  A: 
somelist.ToLookup(x => x.GroupingString)
leppie
How do I get a List/Array's out of the Grouping that generates?
Dan Neely
@Dan Neely: You can either iterate and use the `Key` property, or do a direct lookup using the indexer (think it uses a backing Dictionary). If you dont need the key, I would probably go with Mehrdad Afshari suggestion.
leppie
Am I missing something? This crashes when I try to iterate the results and cast them back into a list:foreach (List<MyStruct> foo in someList.ToLookup(x => x.ident))
Dan Neely
@Dan Neely: `IEnumerable<MyStruct>`
leppie