fork download
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4.  
  5. public class Test
  6. {
  7.  
  8. public static Func<T,T,bool> MakeComparator<T>() {
  9. var lhs = Expression.Parameter(typeof (T), "lhs");
  10. var rhs = Expression.Parameter(typeof (T), "rhs");
  11. var allPropChecks = typeof(T)
  12. .GetProperties()
  13. .Where(p => p.CanRead && p.GetIndexParameters().Length == 0)
  14. .Select(p => Expression.Equal(Expression.Property(lhs, p), Expression.Property(rhs, p)))
  15. .ToList();
  16. Expression compare;
  17. if (allPropChecks.Count == 0) {
  18. return (a,b) => true; // Objects with no properties are the same
  19. } else {
  20. compare = allPropChecks[0];
  21. compare = allPropChecks
  22. .Skip(1)
  23. .Aggregate(compare, Expression.AndAlso);
  24. }
  25. return (Func<T, T, bool>)Expression.Lambda(compare, new[] { lhs, rhs }).Compile();
  26. }
  27. class Point3D {
  28. public int X { get; set; }
  29. public int Y { get; set; }
  30. public int Z { get; set; }
  31. }
  32. public static void Main() {
  33. var cmp = MakeComparator<Point3D>();
  34. var p1 = new Point3D {X = 1, Y = 2, Z = 3};
  35. var p2 = new Point3D { X = 1, Y = 2, Z = 3 };
  36. var p3 = new Point3D { X = 1, Y = 3, Z = 1 };
  37. Console.WriteLine(cmp(p1, p2));
  38. Console.WriteLine(cmp(p2, p3));
  39. }
  40. }
Success #stdin #stdout 0.07s 34488KB
stdin
Standard input is empty
stdout
True
False