合并C#中的字典合并两个或更多字典的最佳方法是什么(Dictionary<T1,T2>)在C#中(像LINQ这样的3.0特性很好)。我正在考虑一个方法签名,大意是:public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);或public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);编辑:从JaredPar和JonSkeet那里得到了一个很酷的解决方案,但是我在想一些处理重复密钥的方法。在冲突的情况下,只要是一致的,哪个值被保存到DECT中并不重要。
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
var result = dictionaries.SelectMany(dict => dict) .ToDictionary(pair => pair.Key, pair => pair.Value);
var result = dictionaries.SelectMany(dict => dict) .ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First());
MMMHUHU
TA贡献1834条经验 获得超8个赞
public static class DictionaryExtensions{ // Works in C#3/VS2008: // Returns a new dictionary of this ... others merged leftward. // Keeps the type of 'this', which must be default-instantiable. // Example: // result = map.MergeLeft(other1, other2, ...) public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others) where T : IDictionary<K,V>, new() { T newMap = new T(); foreach (IDictionary<K,V> src in (new List<IDictionary<K,V>> { me }).Concat(others)) { // ^-- echk. Not quite there type-system. foreach (KeyValuePair<K,V> p in src) { newMap[p.Key] = p.Value; } } return newMap; }}
- 3 回答
- 0 关注
- 1407 浏览
添加回答
举报
0/150
提交
取消