Group into a dictionary of elements
Hi I have a list of element of class type class1 as show below. How do I group them into a
Dictionary<int,List<SampleClass>>
based on the groupID
class SampleClass
{
public int g开发者_如何学JAVAroupID;
public string someData;
}
I have done this way:
var t =(from data in datas group data by data.groupID into dataGroups select dataGroups).ToDictionary(gdc => gdc.ToList()[0].groupID, gdc => gdc.ToList());
Is there a better way of doing thiss
It will be more efficient to replace:
gdc => gdc.ToList()[0].groupID
with:
gdc => gdc.Key
Other than that, it looks like I would have done.
Alternately, if you are okay with extension methods over LINQ (I personally prefer them), it can be shortened further still with:
var t = data.GroupBy(data => data.groupID).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
精彩评论