c#合併Dictionary

合併方法在:

http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp

var result = dictionaries.SelectMany(dict => dict)
                         .ToDictionary(pair => pair.Key, pair => pair.Value);

之前也沒不瞭解lambda和linq, 就一塊看了

看msdn的解釋是=>左邊是參數, 右邊是返回值


string[] digits = { "zero", "one", "two", "three", "four", "five", 
                    "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);

Where兩個重載:

Where(OfTSource)(IEnumerable(Of TSource), Func(OfTSource, Boolean))

Where(OfTSource)(IEnumerable(Of TSource), Func(OfTSource, Int32, Boolean))

Func的最後一個參數都是返回值類型

所以上面的Where是第二個重載, 選出string長度小於其在序列中位置的


selectMany的解釋:

Projects each element of a sequence to an IEnumerable(OfT) and flattens the resulting sequences into one sequence.

即如果返回值是一些序列的話, 就把這些序列合併


所以合併Dict就是

var dictionaries = new List< Dictionary<TKey, TValue> >(){ dict1, dict2, dict3, ... }.selectMany(dict => dict).toDictionary(pair => pair.key, pair => pair.value);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章