leora
leora

Reputation: 196761

why doesn't .Except() and Intersect() work here using LINQ?

i have the following code which doesnt seem to be working:

Context: I have two lists of objects:
* listOne has 100 records
* listTwo has 70 records

many of them have the same Id property (in both lists);

 var listOneOnlyItems = listOne.Except(listTwo, new ItemComparer ());

here is the comparer

public class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item x, Item y)
    {
        if (x.Id == y.Id)
            return true;

        return false;
    }

    public int GetHashCode(Item obj)
    {
        return obj.GetHashCode();
    }
}

after i run this code and look into the results

listOneOnlyItems 

still has 100 records (should only have 30). Can anyone help me?

also, running

    IEnumerable<Item> sharedItems = listOne.Intersect(listTwo, new ItemComparer());

returns zero reesults in the sharedItems collection

Upvotes: 2

Views: 1934

Answers (3)

Rafe
Rafe

Reputation: 5295

This code works fine:

static void TestLinqExcept()
{
    var seqA = Enumerable.Range(1, 10);
    var seqB = Enumerable.Range(1, 7);
    var seqAexceptB = seqA.Except(seqB, new IntComparer());
    foreach (var x in seqAexceptB)
    {
        Console.WriteLine(x);
    }
}

class IntComparer: EqualityComparer<int>
{
    public override bool Equals(int x, int y)
    {
        return x == y;
    }

    public override int GetHashCode(int x)
    {
        return x;
    }
}

You need to add 'override' keywords to your EqualityComparer methods. (I think not having 'override' as implicit was a mistake on the part of the C# designers).

Upvotes: 0

PeterL
PeterL

Reputation: 1397

public int GetHashCode(Item obj)
{
    return obj.Id.GetHashCode();
}

Worth a check at least -- IIRC GetHashCode() is tested first before equality, and if they don't have the same hash it won't bother checking equality. I'm not sure what to expect from obj.GetHashCode() -- it depends on what you've implemented on the Item class.

Upvotes: 6

Kirk Woll
Kirk Woll

Reputation: 77606

Consider making GetHashCode() return obj.Id.GetHashCode()

Upvotes: 0

Related Questions