17

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.

Yuck
  • 49,664
  • 13
  • 105
  • 135
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 2
    ToString returns the type's name when not overridden so it wouldn't be a good way to compare items :) – vc 74 Feb 13 '12 at 17:05
  • By the way, you can't pass your own `IEqualityComparer` into the `List.Contains` method. You *can* pass your own comparer into LINQ's `Contains` extension method, which works quite happily against `List`. – LukeH Feb 13 '12 at 17:10

3 Answers3

18

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.

Yuck
  • 49,664
  • 13
  • 105
  • 135
  • One exception to this is if you search for `null`, in which case `Contains` just does an `item == null` test directly rather than using the comparer. – LukeH Feb 13 '12 at 17:02
5

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

heisenberg
  • 9,665
  • 1
  • 30
  • 38
1

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009