fork download
  1. using System;
  2. using System.Reflection;
  3. using System.Linq.Expressions;
  4.  
  5. public class TestDTO
  6. {
  7. public string StringValue { get; set; }
  8. public int IntValue { get; set; }
  9. }
  10.  
  11. public class TestDataClass
  12. {
  13. public string StringValue { get; set; }
  14. public int IntValue { get; set; }
  15. public string AnotherStringValue { get; set;}
  16. }
  17.  
  18. public class Test
  19. {
  20. public static bool AreEqual<TDTO, TDATA>(TDTO dto, TDATA data)
  21. {
  22. foreach(var prop in typeof(TDTO).GetProperties())
  23. {
  24. var dataProp = typeof(TDATA).GetProperty(prop.Name);
  25. if (dataProp == null)
  26. throw new InvalidOperationException(string.Format("Property {0} is missing in data class.", prop.Name));
  27. var compExpr = GetComparisonExpression(prop, dataProp);
  28. var del = compExpr.Compile();
  29. if (!(bool)del.DynamicInvoke(dto, data))
  30. return false;
  31. }
  32. return true;
  33. }
  34.  
  35. private static LambdaExpression GetComparisonExpression(PropertyInfo dtoProp, PropertyInfo dataProp)
  36. {
  37. var dtoParam = Expression.Parameter(dtoProp.DeclaringType, "dto");
  38. var dataParam = Expression.Parameter(dataProp.DeclaringType, "data");
  39. return Expression.Lambda(
  40. Expression.MakeBinary(ExpressionType.Equal,
  41. Expression.MakeMemberAccess(
  42. dtoParam, dtoProp),
  43. Expression.MakeMemberAccess(
  44. dataParam, dataProp)), dtoParam, dataParam);
  45. }
  46.  
  47. public static void Main()
  48. {
  49. var dto = new TestDTO() { StringValue = "Test", IntValue = 1 };
  50. var data = new TestDataClass() { StringValue = "Test", IntValue = 1 };
  51. Console.WriteLine("AreEqual = {0}", AreEqual(dto, data));
  52. var otherData = new TestDataClass() { StringValue = "SomeOtherValue", IntValue = 3 };
  53. Console.WriteLine("AreEqual = {0}", AreEqual(dto, otherData));
  54. }
  55. }
Success #stdin #stdout 0.08s 34368KB
stdin
Standard input is empty
stdout
AreEqual = True
AreEqual = False