I have a class which has 3 properties and when it's being evaluated for equality, I only want 2 of them be accounted for. That means, in the following Product
class, Misc
should have no role in equality comparison.
However, when the code runs, only apple 9 a
is displayed. But I also want apple 9 b
be displayed too. So what is wrong in the code?
namespace ConsoleApplication1
{
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
public string Misc { get; set; }
}
class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false;
return x.Code == y.Code && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
if (Object.ReferenceEquals(product, null)) return 0;
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
int hashProductCode = product.Code.GetHashCode();
return hashProductName ^ hashProductCode;
}
}
class Program
{
static void Main(string[] args)
{
Product[] store1 = { new Product { Name = "apple", Code = 9, Misc = "a" },
new Product { Name = "orange", Code = 4 , Misc = "c"} };
Product[] store2 = { new Product { Name = "apple", Code = 9, Misc = "b" },
new Product { Name = "lemon", Code = 12, Misc = "d" } };
IEnumerable<Product> duplicates = store1.Intersect(store2, new ProductComparer());
foreach (var product in duplicates)
Console.WriteLine(product.Name + " " + product.Code + " " + product.Misc);
Console.Read();
}
}
}