Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 groupID;
   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

question from:https://stackoverflow.com/questions/5414813/group-into-a-dictionary-of-elements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
96 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...