如何名单< T>。载()查找匹配的项目? [英] How Does List<T>.Contains() Find Matching Items?

查看:141
本文介绍了如何名单< T>。载()查找匹配的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有车对象的列表

 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.

这篇关于如何名单&LT; T&GT;。载()查找匹配的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆