简体   繁体   中英

To Get Different values by comparing two objects in C#

I have two objects of the same class type and I want to fetch the different valued columns with values from both the objects.

I have tried the below code but I'm able to fetch only the column names.

public List<string> GetChangedProperties<T>(T a, T b) where T : class
{
    if (a != null && b != null)
    {
        if (object.Equals(a, b))
        {
            return new List<string>();
        }

        var allProperties = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        return allProperties.Where(p => !object.Equals(p.GetValue(a), p.GetValue(b))).Select(p => p.Name).ToList();
    }
    else
    {
        var aText = $"{(a == null ? ("\"" + nameof(a) + "\"" + " was null") : "")}";
        var bText = $"{(b == null ? ("\"" + nameof(b) + "\"" + " was null") : "")}";
        var bothNull = !string.IsNullOrEmpty(aText) && !string.IsNullOrEmpty(bText);
        throw new ArgumentNullException(aText + (bothNull ? ", " : "") + bText);
    }
}

You can use a Dictionary instead of a List:

public class Program
{

  static public Dictionary<string, Tuple<object, object>> GetChangedProperties<T>(T a, T b) where T : class
  {
    if ( a != null && b != null )
    {
      if ( Object.Equals(a, b) )
      {
        return new Dictionary<string, Tuple<object, object>>();
      }
      var allProperties = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
      var result = new Dictionary<string, Tuple<object, object>>();
      foreach ( var p in allProperties )
      {
        var v1 = p.GetValue(a);
        var v2 = p.GetValue(b);
        if ( !Object.Equals(v1, v2) )
          result.Add(p.Name, new Tuple<object, object>(v1, v2));
      }
      return result;
    }
    else
    {
      var aText = $"{( a == null ? ( "\"" + nameof(a) + "\"" + " was null" ) : "" )}";
      var bText = $"{( b == null ? ( "\"" + nameof(b) + "\"" + " was null" ) : "" )}";
      var bothNull = !string.IsNullOrEmpty(aText) && !string.IsNullOrEmpty(bText);
      throw new ArgumentNullException(aText + ( bothNull ? ", " : "" ) + bText);
    }
  }

  public class Test
  {
    public int A { get; set; }
    public int B { get; set; }
  }

  static void Main(string[] args)
  {

    var v1 = new Test { A = 10, B = 20 };
    var v2 = new Test { A = 5, B = 20 };

    var list = GetChangedProperties(v1, v2);

    foreach ( var item in list )
      Console.WriteLine($"{item.Key}: {item.Value.Item1.ToString()} != {item.Value.Item2.ToString()}");

    Console.ReadKey();
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM