简体   繁体   English

列出字典 <Key, List<Value> &gt;-C#

[英]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: 一般而言,查找要干净得多:

  • They're immutable, whereas your approach ends up with lists which can be modified 它们是不可变的,而您的方法最终得到可以修改的列表
  • They express in the type system exactly what you're trying to express (one key to multiple values) 它们在类型系统中准确表达您要表达的内容(一个指向多个值的键)
  • They make looking keys up easier by returning an empty sequence of values for missing keys, rather than throwing an exception 通过为缺失的键返回空值序列,而不是引发异常,它们使查找键更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM