Aaron Thompson
Aaron Thompson

Reputation: 1889

Using IEqualityComparer to compare two lists

I am trying to compare two c# Lists containing complex objects. I am aware similar questions have been asked before but this is slightly different. I am following the MSDN example to the letter: https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx

public class ProductA
{ 
    public string Name { get; set; }
    public int Code { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{

    public bool Equals(ProductA x, ProductA y)
    {
        //Check whether the objects are the same object. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether the products' properties are equal. 
        return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name);
    }

    public int GetHashCode(ProductA obj)
    {
        //Get hash code for the Name field if it is not null. 
        int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();

        //Get hash code for the Code field. 
        int hashProductCode = obj.Code.GetHashCode();

        //Calculate the hash code for the product. 
        return hashProductName ^ hashProductCode;
    }
}

Then using the Except method to remove "apple" 9 from the list

ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 }, 
                       new ProductA { Name = "orange", Code = 4 },
                        new ProductA { Name = "lemon", Code = 12 } };

ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } };

//Get all the elements from the first array //except for the elements from the second array. 
IEnumerable<ProductA> except = fruits1.Except(fruits2);

foreach (var product in except)
    Console.WriteLine(product.Name + " " + product.Code);

This code should produce the following output: orange 4 lemon 12

Mine does not and prints out the following: apple 9 orange 4 lemon 12

Upvotes: 6

Views: 8305

Answers (1)

Aaron Thompson
Aaron Thompson

Reputation: 1889

There appears to be an error in the MSDN documentation: https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx

The Except method call should use the IEqualityComparer:

//Get all the elements from the first array //except for the elements from the second array. 
ProductComparer pc = new ProductComparer();
IEnumerable<ProductA> except = fruits1.Except(fruits2, pc);

Upvotes: 7

Related Questions