Intersect between two lists not working

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?

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());

Need Your Help

MySQL sum from two joined tables and multiple rows - need to bring out total or all rows

mysql join sum

I have the following query which works fine when bringing out the total price of each order (thanks to the stackoverflow community):

Information about debugging engines used by the debugger

.net visual-studio envdte vsix vspackage

In Visual Studio, if you want to attach debugger to any processes, you have the possibility to select some specific engine (code type) or set of engines you would like to use: