public static bool Compare<T>(this T source, T other, params Expression<Func<T>>[] propertiesToSkip)
{
PropertyInfo[] sourceProperties = source.GetType().GetProperties();
List<string> lstPropertiesToSkip = (from x in propertiesToSkip select ((MemberExpression)((UnaryExpression)x.Body).Operand).Member.Name).ToList();
return !(sourceProperties.Any(sourcePropertyInfo => !lstPropertiesToSkip.Contains(sourcePropertyInfo.Name) && (!sourcePropertyInfo.GetValue(source, null).Equals(sourcePropertyInfo.GetValue(other, null)))));
}
I want this feature to be called.
var source = new MyClass();
var other = new MyClass();
source.Compare<MyClass>(other, ()=>SkipProperty1, ()=>SkipProperty2);
Problem :() => SkipProperty1 and () => SkipProperty2 are not of type MyClass. I need:
Compare <A,B,C,D...>
params Expression<Func<T>>[] where T is A,B,C,D,E...
I looked at AutoMapper with smooth syntax.
public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions);
Mapper.CreateMap<MyClass, MyClass>()
.ForMember(dest => dest.Property1, opt => opt.Ignore())
.ForMember(dest => dest.Property2, opt => opt.Ignore()));
- Can I change the signature of Compare to make the function work?
- Is there any other way to solve this? For example, using free syntax
Note. I do not want to send property names as strings.