The Intersect should have yielded 0 records because firstname and lastname do not macth. Where did I go wrong....? I suspect is in the equals implementation.
Thankyou all the problem is solved ( special thanks to Lasse V. Karlsen right on the money with the gethashcode ): Equals plus the hashcode mistake fixed the problem.
Test Code
var test1 = new ClassA { employeeid = 1, firstName = "a", lastname = "a" };
var test2 = new ClassA { employeeid = 1, firstName = "a", lastname = "b" };
IList<ClassA> listA = new List<ClassA>();
listA.Add(test1);
IList<ClassA> listB = new List<ClassA>();
listB.Add(test2);
//Actual Code
var Reflection = new ReflectionHelper();
var ListClassA = Reflection.GetPropertyNames<ClassA>();
var results = listA.Intersect(listB, new Compare<ClassA>(ListClassA)).ToList();
My comparer
public class KeyComparerAttribute : Attribute{}
public class Compare<T> : IEqualityComparer<T> where T : class
{
IList<string> keyProperties = new List<string>();
public Compare(IList<string> keyProperties)
{
this.keyProperties = keyProperties;
}
public bool Equals(T x, T y)
{
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
return false;
}
var reflection = new ReflectionHelper();
foreach (var propName in keyProperties)
{
string val1 = reflection.GetPropertyValue<T>(propName, x);
string val2 = reflection.GetPropertyValue<T>(propName, y);
if (!val1.Equals(val2))
{
return false;
}
}
//if never false then it must be true....
return true;
}
public int GetHashCode(T obj)
{
int hash = 17;
foreach (var propInfo in keyProperties)
{
var myValue = reflection.GetPropertyValue(propName:propInfo, src: obj);
hash = hash * 23 + myValue.GetHashCode();
}
return hash;
}
}
My helper classes just for reference
public class ReflectionHelper
{
public IList<string> GetPropertyNames<T>()
{
IList<string> propertyNames = new List<string>();
var propertyInfos = typeof(T).GetProperties(
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Default |
BindingFlags.Instance).ToList().
Where(prop => Attribute.IsDefined(prop, typeof(KeyComparerAttribute)));
// write property names
if (propertyInfos.ToList().Count > 0)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
propertyNames.Add(propertyInfo.Name);
}
}
return propertyNames;
}
public string GetPropertyValue<T>(string propName, T src)
{
return src.GetType().GetProperty(propName).GetValue(src, null).ToString();
}
}
Class A
public class ClassA
{
public int employeeid { get; set; }
[KeyComparer]
public string firstName { get; set; }
[KeyComparer]
public string lastname { get; set; }
}