How to compare two Dictionaries in C#

后端 未结 11 1273
南方客
南方客 2020-12-05 10:03

I have two Generic Dictionaries.Both have same keys.But values can be different.I want to compare 2nd dictionary with 1st dictionary .If there are differences between values

11条回答
  •  北海茫月
    2020-12-05 10:30

    In recent C# versions you can try

            public static Dictionary ValueDiff(this Dictionary dictionary,
                Dictionary otherDictionary)
            {
                IEnumerable<(TK key, TV otherValue)> DiffKey(KeyValuePair kv)
                {
                    var otherValue = otherDictionary[kv.Key];
                    if (!Equals(kv.Value, otherValue))
                    {
                        yield return (kv.Key, otherValue);
                    }
                }
    
                return dictionary.SelectMany(DiffKey)
                    .ToDictionary(t => t.key, t => t.otherValue, dictionary.Comparer);
            }
    

    I am not sure that SelectManyis always the fastest solution, but it is one way to only select the relevant items and generate the resulting entries in the same step. Sadly C# does not support yield return in lambdas and while I could have constructed single or no item collections, I choose to use an inner function.

    Oh and as you say that the keys are the same, it may be possible to order them. Then you could use Zip

            public static Dictionary ValueDiff(this Dictionary dictionary,
                Dictionary otherDictionary)
            {
                return dictionary.OrderBy(kv => kv.Key)
                    .Zip(otherDictionary.OrderBy(kv => kv.Key))
                    .Where(p => !Equals(p.First.Value, p.Second.Value))
                    .ToDictionary(p => p.Second.Key, p => p.Second.Value, dictionary.Comparer);
            }
    

    Personally I would tend not to use Linq, but a simple foreach like carlosfigueira and vanfosson:

            public static Dictionary ValueDiff2(this Dictionary dictionary,
                Dictionary otherDictionary)
            {
                var result = new Dictionary(dictionary.Count, dictionary.Comparer);
                foreach (var (key, value) in dictionary)
                {
                    var otherValue = otherDictionary[key];
                    if (!Equals(value, otherValue))
                    {
                        result.Add(key, otherValue);
                    }
                }
    
                return result;
            }
    

提交回复
热议问题