简体   繁体   English

如何列出 <T> .Contains()查找匹配项目?

[英]How Does List<T>.Contains() Find Matching Items?

I have a list of car objects 我有一个汽车对象列表

 List<Car> cars = GetMyListOfCars();

and i want to see if a car is in the list 我想知道一辆车是否在列表中

if (cars.Contains(myCar))
{
}

what does Contains use to figure out if myCar is in the list. 包含什么用于确定myCar是否在列表中。 Does it do a "ToString()" on my car object. 它是否在我的汽车对象上执行“ToString()”。 Does it use the Equals() method, the gethashcode()? 它是否使用Equals()方法,gethashcode()?

I see i can pass in my own IEqualityComparer to force my own implementation but just wanted to understand what it does by default. 我看到我可以通过我自己的IEqualityComparer来强制我自己的实现,但只是想了解它默认情况下的作用。

Straight from MSDN - List<T>.Contains: 直接来自MSDN - 列出<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). 此方法通过使用默认的相等比较器来确定相等性,该默认的相等比较器由对象的T的IEquatable(Of T).Equals方法的实现(列表中的值的类型)定义。

This method performs a linear search; 该方法执行线性搜索; therefore, this method is an O(n) operation, where n is Count. 因此,该方法是O(n)操作,其中n是Count。

So in the end it depends on how T implements IEquatable.Equals() . 所以最终它取决于T如何实现IEquatable.Equals() For most objects this is going to be a reference comparison, unless overriden. 对于大多数对象,这将是一个参考比较,除非重写。 Same location in memory is the same object. 内存中的相同位置是同一个对象。

It uses Equals() 它使用Equals()

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). 此方法通过使用默认的相等比较器来确定相等性,该默认的相等比较器由对象的T的IEquatable(Of T).Equals方法的实现(列表中的值的类型)定义。

http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx

Contains will return true as soon as it can - that is once the first item that fits the criteria is found. Contains将尽快返回true - 即一旦找到符合条件的第一个项目。

A false will be returned after all items have been iterated over. 迭代完所有项目后将返回false

In regards to how it does that - it will use reference equality for reference types if you do not override Equals . 关于它是如何做的 - 如果你不重写Equals ,它将使用引用类型的引用相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM