[英]C# - Convert List to Dictionary with Value as List
So i read this LINQ - Convert List to Dictionary with Value as List but am not able to get it working.所以我读了这个LINQ - Convert List to Dictionary with Value as List但我无法让它工作。
According to that post, I should be able to convert a list of items where several of them have the same key to a dictionary <int, List<>)根据那篇文章,我应该能够将其中几个项目具有相同键的项目列表转换为字典 <int, List<>)
List<MyObject> list = ...;
var map = list
.GroupBy(x => x.KeyedProperty)
.ToDictionary(x => x.Key, x => x.ToList());
I have我有
MyObject
{
int OwnerId { get; set; }
string Description { get; set; }
}
List<MyObject> myObjects;
Now I want a dictionary with all objects that have the same OwnerId.现在我想要一个包含所有具有相同 OwnerId 的对象的字典。
Dictionary<int, List<MyObjects> myObjects = ...
I tried to do我试着做
myObjects.GroupBy(x => x.OwnerId).ToDictionary(x => x.OwnerId, x => x.ToList());
problem is GroupBy returns a IGrouping<int, MyObject> and IGrouping does not have a property OwnerId.问题是 GroupBy 返回 IGrouping<int, MyObject> 而 IGrouping 没有属性 OwnerId。 What did I miss?
我错过了什么?
You need to use .Key
instead of .OwnerId
when you are creating a dictionary.创建字典时需要使用
.Key
而不是.OwnerId
。
var resultantDictionary = myObjects
.GroupBy(x => x.OwnerId)
.ToDictionary(x => x.Key, x => x.ToList());
//^^^^ use .Key instead of .OwnerId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.