在带有分组的列表上创建字典 [英] Create a dictionary on a list with grouping
本文介绍了在带有分组的列表上创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在列表中有以下对象:
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>>
我想通过属性 GroupKey
对 List
进行分组,但我不明白这是如何完成的以及一些帮助.
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());
这个可以用!!!
这篇关于在带有分组的列表上创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文