Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect between two lists not working

Tags:

c#

list

linq

I have two lists see below.....result is coming back as empty

List<Pay>olist = new List<Pay>();
List<Pay> nlist = new List<Pay>();
Pay oldpay = new Pay()
{
    EventId = 1,
    Number = 123,                        
    Amount = 1
};

olist.Add(oldpay);
Pay newpay = new Pay ()
{
   EventId = 1,
    Number = 123,                        
    Amount = 100
};
nlist.Add(newpay);
var Result = nlist.Intersect(olist);

any clue why?

like image 686
user570715 Avatar asked Nov 29 '11 17:11

user570715


1 Answers

You need to override the Equals and GetHashCode methods in your Pay class, otherwise Intersect doesn't know when 2 instances are considered equal. How could it guess that it is the EventId that determines equality? oldPay and newPay are different instances, so by default they're not considered equal.

You can override the methods in Pay like this:

public override int GetHashCode()
{
    return this.EventId;
}

public override bool Equals(object other)
{
    if (other is Pay)
        return ((Pay)other).EventId == this.EventId;
    return false;
}

Another option is to implement an IEqualityComparer<Pay> and pass it as a parameter to Intersect:

public class PayComparer : IEqualityComparer<Pay>
{
    public bool Equals(Pay x, Pay y)
    {
        if (x == y) // same instance or both null
            return true;
        if (x == null || y == null) // either one is null but not both
            return false;

        return x.EventId == y.EventId;
    }


    public int GetHashCode(Pay pay)
    {
        return pay != null ? pay.EventId : 0;
    }
}

...

var Result = nlist.Intersect(olist, new PayComparer());
like image 80
Thomas Levesque Avatar answered Sep 28 '22 13:09

Thomas Levesque