Group into a dictionary of elements

笑着哭i 提交于 2019-12-20 10:18:00

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/5414813/group-into-a-dictionary-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!