I am writing this neat class implementing IEqualityComparer, so that I can just pass any anonymous type to it (or actually any type with properties) and it will automatically compare the types by comparing the property values of the types.
public class CompareProperty<T> : IEqualityComparer<T>
{
private Type type;
private PropertyInfo propInfo;
private string _fieldName;
public string fieldName
{
get;
set;
}
public CompareProperty(string fieldName)
{
this.fieldName = fieldName;
}
public bool Equals<T>(T x, T y)
{
if (this.type == null)
{
type = x.GetType();
propInfo = type.GetProperty(fieldName);
}
object objX = propInfo.GetValue(x, null);
object objY = propInfo.GetValue(y, null);
return objX.ToString() == objY.ToString();
}
}
I thought this was a nice little helper function I could use many times.
In order to use this, I have to do:
var t = typeof(CompareProperty<>);
var g = t.MakeGenericType(infoType.GetType());
var c = g.GetConstructor(new Type[] {String.Empty.GetType()});
var obj = c.Invoke(new object[] {"somePropertyName"});
Fair enough, but what do I do with the obj variable it returns?
someEnumerable.Distinct(obj);
The overload of the distinct extension function does not accept this, because it does not see a IEqualityComparer type, it only sees an object, of course.
someEnumerable.Distinct((t) obj);
someEnumerable.Distinct(obj as t);
This also doesn't work. Type/Namespace not found (red underline).
How do I get this straight?