Difference between Find, Exists and Contains of the List<T> class

Asked

Viewed 330 times

5

I’m working with the class List<T>, so I came across some research methods, if I may call it:

  1. Find;
  2. Exists;
  3. Contains;

I was in doubt of what the difference between them, so I searched on the Microsoft site: List Class, I came to the following conclusion:

  1. Find : Looks for an element that matches the settings, and returns the first value of the list.
  2. Exists : Determines whether there is an element matching the definitions.
  3. Contains : Determines whether there is an element that corresponds to ALL definitions.

Could you give me a better explanation of the 3 methods? I believe it is one that confuses the less experienced.

2 answers

4


  1. Find: Looks for an element that matches the settings, and returns the first value of the list.

Correct. Better said, it corresponds to the predicate passed as parameter.

  1. Exists: Determines whether there is an element matching the definitions.

Yes, but also item 1.

  1. Contains: Determines whether there is an element that corresponds to ALL definitions.

It would be better to say "whether the compared element is contained in the list or not".

For comparison, it is usually used EqualityComparer<T>.Default, which compares the references of the objects involved in the iterations. For simple variables it works well. For complex objects, it is recommended to write a specific comparator in order to compare, for example, property to property.

0

Explaining the same with other words.

Find: Find an element that matches the settings, and returns the first value of the list.

NAY. It returns all elements - not just the first, it returns a list - that satisfy the query of the predicate.

Exists: Determines whether there is an element that matches the settings.

Returns true when it finds the first element that satisfies query of the predicate. This is important because it does not scroll through all the items in the list, but in the first instance, it already returns true.

Contains: Determines whether there is an element that matches ALL definitions.

Returns true, not "if there is an element," but yes if there is an element. The Contains() expects to receive an object of the same type from the list, and returns saying whether that object - the very same instance of the object - is contained in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.