与分组列表上创建一个字典 [英] Create a dictionary on a list with grouping
本文介绍了与分组列表上创建一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表中的下列对象:
公共类DemoClass
{
公众诠释GroupKey {获得;组; }
公共字符串DemoString {获得;组; }
公共对象SomeOtherProperty {获得;组; }
}
现在,我想创建以下字典出来的:
词典< INT,名单,其中,DemoClass>>
我想组名单,其中,DemoClass>
由酒店 GroupKey
,但我不明白怎么做到这一点,并有所帮助。
想了一下后,我和取得所需的行为:
VAR groupedDemoClasses =从demoClass在mySepcialVariableWhichIsAListOfDemoClass
组demoClass由demoClass.GroupKey
进入groupedDemoClass
选择groupedDemoClass;
变种neededDictionary = groupedDemoClass.ToDictionary(GDC => gdc.Key,GDC => gdc.ToList());
不过,是有办法使它成为一个单独的语句?
解决方案
VAR groupedDemoClasses =(从demoClass在mySepcialVariableWhichIsAListOfDemoClass
组demoClass由demoClass.GroupKey
进入groupedDemoClass
选择groupedDemoClass).ToDictionary(GDC => gdc.Key,GDC => gdc.ToList());
这人会工作!
I have the following object in a list:
public class DemoClass
{
public int GroupKey { get; set; }
public string DemoString { get; set; }
public object SomeOtherProperty { get; set; }
}
Now, I want to create following dictionary out of it:
Dictionary<int, List<DemoClass>>
I want to group the List<DemoClass>
by the property GroupKey
, but I don't understand how this is done and some help.
After thinking a bit, I achieved the needed behaviour with:
var groupedDemoClasses = from demoClass in mySepcialVariableWhichIsAListOfDemoClass
group demoClass by demoClass.GroupKey
into groupedDemoClass
select groupedDemoClass;
var neededDictionary = groupedDemoClass.ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
but, is there a way to make this into a single statement?
解决方案
var groupedDemoClasses = (from demoClass in mySepcialVariableWhichIsAListOfDemoClass
group demoClass by demoClass.GroupKey
into groupedDemoClass
select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
This one will work !!!
这篇关于与分组列表上创建一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文