【发布时间】:2010-10-30 14:20:12
【问题描述】:
我在列表中有以下对象:
public class DemoClass
{
public int GroupKey { get; set; }
public string DemoString { get; set; }
public object SomeOtherProperty { get; set; }
}
现在,我想从中创建以下字典:
Dictionary<int, List<DemoClass>>
我想按属性GroupKey 对List<DemoClass> 进行分组,但我不明白这是如何完成的,需要一些帮助。
经过一番思考,我实现了所需的行为:
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());
但是,有没有办法把它变成一条语句?
【问题讨论】: