如何名单< T>。载()查找匹配的项目?名单、项目、LT、GT

2023-09-05 23:13:36 作者:不爱就滚开

我有车对象的列表

 List<Car> cars = GetMyListOfCars();

和我想看看是否有车在列表

and i want to see if a car is in the list

if (cars.Contains(myCar))
{
}

什么呢包含使用弄清楚,如果myCar是在列表中。是否做了的ToString()我的车对象。是否使用equals()方法,该gethash code()?

what does Contains use to figure out if myCar is in the list. Does it do a "ToString()" on my car object. Does it use the Equals() method, the gethashcode()?

我看,我可以通过我自己的IEqualityComparer逼我自己的实现,但只是想了解它在默认情况下。

I see i can pass in my own IEqualityComparer to force my own implementation but just wanted to understand what it does by default.

推荐答案

直接从 MSDN - 名单,其中,T&GT ;。载:

该方法通过使用默认的平等决定了平等   比较器,通过的对象的实现定义   IEquatable(Of T)中.Equals方法对于T(值的列表中的类型)。

This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable(Of T).Equals method for T (the type of values in the list).

此方法执行线性搜索;因此,此方法是一个   为O(n)操作,其中n是Count。

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

那么到底它取决于 T 工具的 IEquatable.Equals()。对于大多数对象,这是将是一个参考比较,除非覆盖。在存储器相同的位置是相同的对象。

So in the end it depends on how T implements IEquatable.Equals(). For most objects this is going to be a reference comparison, unless overriden. Same location in memory is the same object.