[英]List to Dictionary<Key, List<Value>> - C#
I have a List and MyClass is: 我有一个列表,MyClass是:
public class MyClass
{
public bool Selected { get; set; }
public Guid NoticeID { get; set; }
public Guid TypeID { get; set; }
}
My question is, how do i convert this list into a Dictionary<Guid, List<Guid>>
, where the dictionary key is the GUID from the TypeID
property, and the value is a list of all the NoticeID
values corresponding to that TypeID
. 我的问题是,如何将这个列表转换成
Dictionary<Guid, List<Guid>>
,其中字典键是TypeID
属性的GUID,而值是对应于该TypeID
的所有NoticeID
值的列表。 I have tried like so: 我已经尝试过像这样:
list.GroupBy(p => p.TypeID).ToDictionary(p => p.Key, p => p.ToList())
but this returns a Dictionary <Guid, List<MyClass>>
, and I want a Dictionary<Guid, List<Guid>>
. 但这返回一个
Dictionary <Guid, List<MyClass>>
,而我想要一个Dictionary<Guid, List<Guid>>
。
Well, when you group you can specify the value you want for each element of the group: 好了,当您分组时,可以为分组的每个元素指定所需的值:
var dictionary = list.GroupBy(p => p.TypeID, p => p.NoticeID)
.ToDictionary(p => p.Key, p => p.ToList());
However, I would strongly consider using a lookup instead of a dictionary: 但是,我强烈考虑使用查找而不是字典:
var lookup = list.ToLookup(p => p.TypeID, p => p.NoticeID);
Lookups are much cleaner in general: 一般而言,查找要干净得多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.