Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Does it do a "ToString()" on my car object. Does it use the Equals() method, the 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.

like image 206
leora Avatar asked Feb 13 '12 16:02

leora


People also ask

How contains method work in list?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if a list contains an object?

To check if an element is present in the list, use List. Contains() method.

How does contains work in C#?

C# String Contains() The C# Contains() method is used to return a value indicating whether the specified substring occurs within this string or not. If the specified substring is found in this string, it returns true otherwise false.

How do you check whether a list contains a specific element in C#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.


2 Answers

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.

like image 142
Yuck Avatar answered Sep 21 '22 20:09

Yuck


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

like image 26
heisenberg Avatar answered Sep 19 '22 20:09

heisenberg