How to create a method that takes 2 objects of the same type, properties and compares values

I am trying to create a helper function (for a class) that takes 2 objects and compares a property for both classes

These properties are just simple types like string , int and bool

Using

 Compare(widget1,widget2,x => x.Name) 

What am i still

  private void CompareValue<T>(Order target, Order source, Func<Order, T> selector) { if(target.selector != source.selector) { // do some stuff here } } 

Obviously the code above does not work

Any help would be appreciated, thanks

+5
source share
2 answers

You can add a restriction on IEquatable<T> :

 private void CompareValue<T>(Order target, Order source, Func<Order, T> selector) where T : IEquatable<T> { if (!selector(target).Equals(selector(source)) { // ... Do your stuff } } 

This will handle the types you specified (like many others), and allow the compiler to protect you from use cases, where this is likely to be inappropriate.

Note that to create the resulting value, you also need to call Func<T,U> , that is: selector(target) and selector(source) .

+10
source

If you need a fully general version:

 public void CompareValue<TModel,TProperty>(TModel x, TModel y, Expression<Func<TModel, TProperty>> expression) where TModel : class where TProperty : IEquatable<TProperty> { MemberExpression memberExpression = expression.Body as MemberExpression; Type modelType = typeof(TModel); PropertyInfo propInfo = modelType.GetProperty(memberExpression.Member.Name); TProperty xValue = (TProperty)propInfo.GetValue(x); TProperty yValue = (TProperty)propInfo.GetValue(y); if (xValue.Equals(yValue)) { Console.WriteLine("Match!"); } } 

Using:

 CompareValue(widget1, widget2, x => x.Name); 
+1
source

Source: https://habr.com/ru/post/1209498/


All Articles