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
2010-02-25 16:31:29
ouch!!!!!!!!!!!!!! :)
leppie
2010-02-25 16:31:55
@leppie: why? Isn't this what the OP says he wants? :-?
Mehrdad Afshari
2010-02-25 16:33:04
I'd probably skip the entire second line (keep it as an IEnumerable of IGroupings), but this IS specifically what he asked for. :)
Sapph
2010-02-25 16:36:24
@Mehrdad Afshari: It is correct, but `ToLookup` just does it so much nicer :) OTOH, yours will generate more efficient Linq2SQL. :)
leppie
2010-02-25 16:43:03
@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
2010-02-25 17:00:27
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
2010-02-25 17:10:11