C#字典组成

jam*_*o00 0 .net c# dictionary functional-programming composition

假设我有一份A的仲裁清单

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

...
List<A> theList = ...
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法从列表中组成字典?(如下所示)

Dictionary<string, string> dict = magic(x => x.K, x => x.V, theList)
Run Code Online (Sandbox Code Playgroud)

我不想写下面的代码:

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

ang*_*son 9

就是这样:Enumerable.ToDictionary.

你这样使用它:

Dictionary<string, string> dict = theList.ToDictionary(e => e.K, e => e.V);
Run Code Online (Sandbox Code Playgroud)

  • 他的意思是对于第二个参数,它应该是lambda(=>)而不是equals(=).只是一个错字. (4认同)