【问题标题】:C# Dictionary CompositionC# 字典组合
【发布时间】:2010-02-17 19:47:49
【问题描述】:

假设我有一个 A 的任意列表

class A
{
string K {get;set;}
string V {get;set;}
}

...
List<A> theList = ...

有没有一种简单的方法可以从 theList 编写字典? (类似以下)

Dictionary<string, string> dict = magic(x => x.K, x => x.V, theList)

我不想写下面的代码:

var d = new Dictionary<string, string>
foreach(var blah in theList)
    d[blah.K] = blah.V

【问题讨论】:

    标签: c# .net dictionary functional-programming composition


    【解决方案1】:

    这是:Enumerable.ToDictionary

    你可以这样使用它:

    Dictionary<string, string> dict = theList.ToDictionary(e => e.K, e => e.V);
    

    【讨论】:

    • 不错。我也学到了一些新东西。但我认为应该是e =&gt; e.V
    • @Joel B Fant:不,不应该是e =&gt; e.V。这样做会在 V 上键入字典,值是 A 的实例。
    • 他的意思是,对于第二个参数,它应该是一个lambda(=>)而不是一个等于(=)。只是一个错字。
    • 哎,是的,感谢编辑,当然应该是 lambda 运算符。
    【解决方案2】:

    如果列表是IEnumerable&lt;A&gt;,那么绝对是。您可以在 .NET 3.5 及更高版本的 System.Linq 命名空间中的 Enumerable 类上使用 ToDictionary 扩展方法,如下所示:

    Dictionary<string, string> d = theList.ToDictionary(a => a.K, a => a.V);
    

    这将为您提供一个字典,其中键是 K 属性中的值,值是 V 属性中的值。

    【讨论】:

      【解决方案3】:
      var dict = theList.Cast<A>().ToDictionary(a => a.K, a => a.V);
      

      【讨论】:

        【解决方案4】:
        Dictionary<string, string> dict = theList.ToDictionary( x => x.K , x=> x.V);
        

        【讨论】:

          【解决方案5】:

          Enumarable.ToDictionary&lt;TSource,TKey&gt; 就是你要找的东西:

          theList.ToDictionary(x => x.K, x => x.V);
          

          【讨论】:

          • 为了澄清一点,它是Enumerable.ToDictionary,而不是IEnumerable.ToDictionary
          【解决方案6】:
          Dictionary<string,string> dict = new Dictionary<string,string>();
          
          theList.ForEach( param => dict[param.K] = param.V );
          

          有点短,但基本上还是一个for-each 循环。我更喜欢ToDictionary() 解决方案。

          【讨论】:

          • @Joel B Fant:没有理由这样做,因为 LINQ 为您提供了 ToDictionary 扩展方法。
          • 同意,但我直到现在才知道。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-22
          • 1970-01-01
          相关资源
          最近更新 更多