List.Contains没有像希望的那样工作

时间:2010-06-02 16:23:43

标签: c# list iequalitycomparer

如果我有MyBull类型的对象和List<MyBull> orig

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

orig.add(x);

// Again same? data object
MyBull y = getMeTheObjectWithIdFromDB(9);

为什么这是假的?

// This is false, even though all the properties
// of x and y are the same.
orig.Contains<MyBull>(y); 

4 个答案:

答案 0 :(得分:23)

默认情况下,对象将公开基于引用的相等性。如果您想要自定义规则,例如基于ID字段的相等性,则需要覆盖EqualsGetHashCode方法。

答案 1 :(得分:8)

如果你可以使用LINQ那么你可以

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!");

答案 2 :(得分:4)

这是因为MyBull实例正在通过引用进行比较。从.NET的角度来看,x和y都是不同的实例,因此不是Equal。

为了解决这个问题,你必须override the Equals and GetHashCode methods(这意味着你应该实现IEquatable<MyBull>并覆盖==和!=运算符。)

答案 3 :(得分:3)

你的MyBull对象是否实现IEquatable<T>.Equals?此方法将确定两个对象的相等性

OP要求

您的MyBull类将实现IEquatable

public class MyBull : IEquatable<MyBull>

然后您需要覆盖Equals方法

public bool Equals(MyBull theOtherMyBull)

正如David Neale在下面提到的,当你比较相同类型的物体时,最好使用它 - 你就是这样。重写Object.Equals和Object.GetHashCode也可以。