-
21-09-2019 - |
質問
レッツは、
私はAのarbitrayリストを持っていると言います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
解決
これがあります: Enumerable.ToDictionaryする
あなたはこのようにそれを使用します:
Dictionary<string, string> dict = theList.ToDictionary(e => e.K, e => e.V);
他のヒント
リストは、最も確実IEnumerable<A>
ある場合。
Dictionary<string, string> d = theList.ToDictionary(a => a.K, a => a.V);
どのあなたの鍵はKプロパティの値で、値がVプロパティの値である辞書を与えるだろう。
var dict = theList.Cast<A>().ToDictionary(a => a.K, a => a.V);
Dictionary<string, string> dict = theList.ToDictionary( x => x.K , x=> x.V);
Enumarable.ToDictionary<TSource,TKey>
のあなたが探しているものです。
theList.ToDictionary(x => x.K, x => x.V);
Dictionary<string,string> dict = new Dictionary<string,string>();
theList.ForEach( param => dict[param.K] = param.V );
A少し短いが、それでも基本的にfor-each
ループ。 I ToDictionary()
ソリューションより優れています。
所属していません StackOverflow