List.Contains is not working as hoped

前端 未结 4 1106
[愿得一人]
[愿得一人] 2020-12-06 08:28

If I have an object of type MyBull and a List orig:

// Just an example
MyBull x = getMeTheObjectWithIdFromDB(9);

ori         


        
相关标签:
4条回答
  • 2020-12-06 08:45

    Does your MyBull object implement IEquatable<T>.Equals? This method will determine the equality of two objects

    requested by OP

    Your MyBull class would implement IEquatable

    public class MyBull : IEquatable<MyBull>
    

    and then you would need to override the Equals method

    public bool Equals(MyBull theOtherMyBull)
    

    As David Neale mentions below, this is best used when you're comparing objects of the same type--which you are. Overriding Object.Equals and Object.GetHashCode will work too.

    0 讨论(0)
  • 2020-12-06 08:54

    By default objects will expose reference based equality. If you want custom rules, such as equality based on id fields, you need to override the Equals and GetHashCode methods.

    0 讨论(0)
  • 2020-12-06 09:04

    This is because the MyBull instances are being compared by reference. From the point of view from .NET, x and y are both different instances and therefore not Equal.

    In order to get around this you will have to override the Equals and GetHashCode methods (which means you should probably implement IEquatable<MyBull> and override the == and != operators too).

    0 讨论(0)
  • 2020-12-06 09:12

    If you can use LINQ then you can

    class Vessel
    {
        public int id { get; set; }
        public string name { get; set; }
    }
    

    ...

    var vessels = new List<Vessel>() { new Vessel() { id = 4711, name = "Millennium Falcon" } };
    
    var ship = new Vessel { id = 4711, name = "Millencolin" };
    
    if (vessels.Any(vessel => vessel.id == ship.id))
        Console.Write("There can be only one!");
    
    0 讨论(0)
提交回复
热议问题