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

Voo*_*ild 4 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);
Run Code Online (Sandbox Code Playgroud)

为什么这是假的呢?

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

Sam*_*eff 23

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


Jon*_*röm 8

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

class Vessel
{
    public int id { get; set; }
    public string name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

...

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!");
Run Code Online (Sandbox Code Playgroud)