C# Merging 2 dictionaries

后端 未结 4 1450
半阙折子戏
半阙折子戏 2020-12-31 00:04

I\'m developing an app in C# targeting .NET 3.5. In it, I have 2 similar dictionaries that contain validation criteria for a specific set of elements in my app. Both dicti

4条回答
  •  时光说笑
    2020-12-31 00:37

    If your going to do this a lot, then I'd recommend writing an equality comparer for dictionary keys:

    private class KeyEqualityComparer : IEqualityComparer>
    {
        public bool Equals(KeyValuePair x, KeyValuePair y)
        {
            return x.Key.Equals(y.Key);
        }
    
        public int GetHashCode(KeyValuePair obj)
        {
            return obj.Key.GetHashCode();
        }
    }
    

    And then whenever you need to merge dictionaries, you can do the following

    var comparer = new KeyEqualityComparer();
    dict1 = dict1.Union(dict2,comparer).ToDictionary(a => a.Key, b => b.Value);
    

提交回复
热议问题