分组为元素字典 [英] Group into a dictionary of elements

查看:61
本文介绍了分组为元素字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类类型为class1的元素列表,如下所示.如何将它们分组为

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>>基于组ID

class SampleClass
{
   public int groupID;
   public string someData;
 }                                                                                  

我已经这样做了:

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

推荐答案

替换将更有效:

gdc => gdc.ToList()[0].groupID

具有:

gdc => gdc.Key

除此之外,看来我会做的.

Other than that, it looks like I would have done.

或者,如果您对LINQ的扩展方法没问题(我个人更喜欢它们),则可以使用以下方法将其进一步缩短:

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

这篇关于分组为元素字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆