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.
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.
To check if an element is present in the list, use List. Contains() method.
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.
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With