How to compare two Dictionaries in C#

后端 未结 11 1270
南方客
南方客 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:48

    converting the object to dictionary then following set concept subtract them, result items should be empty in case they are identically.

     public static IDictionary ToDictionary(this object source)
        {
            var fields = source.GetType().GetFields(
                BindingFlags.GetField |
                BindingFlags.Public |
                BindingFlags.Instance).ToDictionary
            (
                propInfo => propInfo.Name,
                propInfo => propInfo.GetValue(source) ?? string.Empty
            );
    
            var properties = source.GetType().GetProperties(
                BindingFlags.GetField |
                BindingFlags.GetProperty |
                BindingFlags.Public |
                BindingFlags.Instance).ToDictionary
            (
                propInfo => propInfo.Name,
                propInfo => propInfo.GetValue(source, null) ?? string.Empty
            );
    
            return fields.Concat(properties).ToDictionary(key => key.Key, value => value.Value); ;
        }
        public static bool EqualsByValue(this object source, object destination)
        {
            var firstDic = source.ToFlattenDictionary();
            var secondDic = destination.ToFlattenDictionary();
            if (firstDic.Count != secondDic.Count)
                return false;
            if (firstDic.Keys.Except(secondDic.Keys).Any())
                return false;
            if (secondDic.Keys.Except(firstDic.Keys).Any())
                return false;
            return firstDic.All(pair =>
              pair.Value.ToString().Equals(secondDic[pair.Key].ToString())
            );
        }
        public static bool IsAnonymousType(this object instance)
        {
    
            if (instance == null)
                return false;
    
            return instance.GetType().Namespace == null;
        }
        public static IDictionary ToFlattenDictionary(this object source, string parentPropertyKey = null, IDictionary parentPropertyValue = null)
        {
            var propsDic = parentPropertyValue ?? new Dictionary();
            foreach (var item in source.ToDictionary())
            {
                var key = string.IsNullOrEmpty(parentPropertyKey) ? item.Key : $"{parentPropertyKey}.{item.Key}";
                if (item.Value.IsAnonymousType())
                    return item.Value.ToFlattenDictionary(key, propsDic);
                else
                    propsDic.Add(key, item.Value);
            }
            return propsDic;
        }
    originalObj.EqualsByValue(messageBody); // will compare values.
    

    source of the code

提交回复
热议问题