我在列表中有以下对象:
public class DemoClass
{
public int GroupKey { get; set; }
public string DemoString { get; set; }
public object SomeOtherProperty { get; set; }
}
现在,我要从中创建以下字典:
Dictionary<int, List<DemoClass>>
我想通过属性
List<DemoClass>
对GroupKey
进行分组,但是我不知道如何完成此操作以及获得一些帮助。经过一番思考,我通过以下方式实现了所需的行为:
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());
但是,有没有办法使它成为单个语句?
最佳答案
var groupedDemoClasses = (from demoClass in mySepcialVariableWhichIsAListOfDemoClass
group demoClass by demoClass.GroupKey
into groupedDemoClass
select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
这将工作!
关于c# - 通过分组在列表上创建字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/938040/