c#合并Dictionary

本文介绍了如何在C#中利用Lambda表达式和LINQ的Where及SelectMany方法合并多个Dictionary。通过示例代码展示了将多个Dictionary合并成一个的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

合并方法在:

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);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值