Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...