Ever wondered which method to choose when one has to check if an element exists in the collection. Well, sooner or later all of us had the same question to ask ourselves and then we use Google, don’t we.
Today, I am going to explain which one to choose between Exists or Contain function when checking the existence of an item in a collection. Let’s take a deep dive into the ocean.
Exists and Contain methods look similar but have got different purpose.
Exists: Determine whether the List<T> contains elements that match the conditions defined by the specified predicate (Microsoft Documentation).
Contains: Determines whether an element is in the List<T>..(Microsoft Documentation).
The return value from both the functions is of type bool but their way of determining / checking the existence of an element is different.
Contain method determine equality by using the default equality comparer. That means with value type such as int, float, one should not implement IEquatable Interface but with reference types such as classes, one should implement IEquatable interface and should provide logic how two objects can be compared. For example, I have an employee class with two public properties; Name and Id. The class implements IEquatable Inteface and it also provides logic to compare two objects. In my case, two objects are said to be equal if both of them have same Name and Id.
- public class Employee: IEquatable < Employee >
- {
-
-
-
- public string Name
- {
- get;
- set;
- }
-
-
-
-
- public int Id
- {
- get;
- set;
- }
-
- public override bool Equals(object other)
- {
- if (other == null) return false;
- return (this.Equals(other));
- }
-
-
-
-
-
- public override int GetHashCode()
- {
- return Id;
- }
-
-
-
-
-
-
- public bool Equals(Employee other)
- {
- if (other == null) return false;
-
- Employee othEmployee = other as Employee;
-
- if (othEmployee == null) return false;
-
- if ((othEmployee.Id == this.Id) && (this.Name == othEmployee.Name))
- {
- return true;
- }
-
- return false;
- }
- }
When list.Contains(Employee emp) is called, equal function in the class operator checks if emp properties Name and Id matches with any item in the collection.
On the other hand, Exists method uses a predicate. Predicate represents a method with a set of criteria. Enumerates over the collection and determines if an element matches the criteria specified.
-
-
-
-
-
-
- private static Predicate < Employee > CheckNameAndId(Employee employee)
- {
- return x = > x.Name == employee.Name && x.Id == employee.Id;
- }
-
-
-
-
-
- private static Predicate < Employee > CheckName(string name)
- {
- return x = > x.Name == name;
- }
You can use Exists method with different types of Predicate, setting different criteria and checking collection against them.
I have attached code for your reference. Download and play around with it. Also, leave your comments if you have any questions.