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

怎甘沉沦 提交于 2019-11-29 13:12:34

Straight from MSDN - List<T>.Contains:

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).

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

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.

It uses 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).

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.

A false will be returned after all items have been iterated over.

In regards to how it does that - it will use reference equality for reference types if you do not override Equals.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!