c#合并Dictionary

来源:互联网 发布:.win域名万网下架 编辑:程序博客网 时间:2024/06/06 19:16

合并方法在:

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(OfTSource), Func(OfTSource, Boolean))

Where(OfTSource)(IEnumerable(OfTSource), 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);




原创粉丝点击