【问题标题】:List<Info> where Info has Last and First properties map to Dictionary<Last,List<First>>List<Info> 其中 Info 具有 Last 和 First 属性映射到 Dictionary<Last,List<First>>
【发布时间】:2013-05-18 18:58:28
【问题描述】:

如果我有一个类型的类

class Info
{
    public Info(string first, string last) { this.First = first; this.Last = last; }
    string First { get; private set; }
    string Last { get; private set; }
}

还有一个列表例如:

var list = new List<Info>();
list.Add(new Info("jon", "doe");
list.Add(new Info("jane", "doe");
list.Add(new Info("bason", "borne");
list.Add(new Info("billy", "nomates");

我想映射到一个排序的姓氏列表,其中包含一个名字列表,即Dictionary&lt;string,List&lt;string&gt;&gt;,其中键是姓氏属性,列表是名字属性列表。

在上面的例子中,我想得到{ "doe" =&gt; { "jon", "jane" }, "borne" =&gt; { "jason" }, "nomates" =&gt; { "billy" } }

是否可以使用 Linq 巧妙地做到这一点,如果可以,我将如何处理?

【问题讨论】:

  • 您提到要对其进行排序,但是您的示例未排序。字典是一个无序的集合。
  • 很好看 - 我不需要任何排序,只需要分组

标签: c# linq linq-to-objects


【解决方案1】:

您可以使用GroupByToDictionary 完成此操作:

首先,公开你的类中的属性,然后使用以下代码:

Dictionary<string, List<string>> names = list
    .GroupBy(x => x.Last)
    .ToDictionary(x => x.Key, x => x.Select(y => y.First).ToList());

【讨论】:

    【解决方案2】:

    对于此类数据,我通常更喜欢使用ILookup&lt;,&gt;。你可以这样构造它:

    list.ToLookup(e => e.Last, e => e.First);
    

    虽然从技术上讲,它不像您要求的那样是 Dictionary&lt;string,List&lt;string&gt;&gt;,但它仍然可以完成您可能想做的大部分事情。

    var firstNamesByLastName = list.ToLookup(e => e.Last, e => e.First);
    foreach(var firstName in firstNamesByLastName["bourne"])
    {
        Console.WriteLine(firstName); // outputs "jason"
    }
    

    请注意,您无法更改 ILookup 对象。因此,您无法在构建后添加新名称。但您希望使用 LINQ 构建它的事实告诉我,您几乎肯定不打算这样做。

    另一个主要的语义差异是,如果您查询 ILookup 中不存在的内容,它将返回一个空集。同样,在这种情况下,这通常是我更喜欢的行为。

    // if this used a dictionary, we'd get an exception.
    foreach(var firstName in firstNamesByLastName["unborne"])
    {
        Console.WriteLine(firstName); // outputs "jason"
    }
    

    【讨论】:

    • 唯一需要注意的是查找是不可变的。
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 2017-03-14
    • 2011-10-05
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2013-03-03
    相关资源
    最近更新 更多