LINQ分组依据为字典对象
问题描述:
我正在尝试使用LINQ从List<CustomObject>
创建Dictionary<string, List<CustomObject>>
.我可以使用"var"使它正常工作,但是我不想使用匿名类型.这就是我所拥有的
I am trying to use LINQ to create a Dictionary<string, List<CustomObject>>
from a List<CustomObject>
. I can get this to work using "var", but I don't want to use anonymous types. Here is what I have
var x = (from CustomObject o in ListOfCustomObjects
group o by o.PropertyName into t
select t.ToList());
我也尝试过使用x
从LINQ库中使用Cast<>()
,但是由于它是无效的强制转换,我遇到了编译问题.
I have also tried using Cast<>()
from the LINQ library once I have x
, but I get compile problems to the effect of it being an invalid cast.
答
Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToDictionary(g => g.Key, g => g.ToList());