Back to: LINQ Tutorial For Beginners and Professionals
LINQ Contains Method in C# with Examples
In this article, I am going to discuss the LINQ Contains Method in C# with Examples. Please read our previous article where we discussed the LINQ Any Method in C# with Examples. As part of this article, we are going to discuss the following pointers.
- What is LINQ Contains Method in C#?
- Multiple Examples to Understand LINQ Contains Method using both Method and Query Syntax.
What is LINQ Contains Method in C#?
The LINQ Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else returns false. There are there Contains Methods available in C# and they are implemented in two different namespaces. They are as follows.
The Contains Method belongs to System.Collections.Generic namespace takes one element as an input parameter and if that element is present in the data source then it returns true else false.
There are two overloaded versions available for the Contains method that belongs to System.Linq namespace and one of the overloaded versions take IEqualityComparer as a parameter.
Note: The Contains method works in a different manner when working with complex type objects. For complex-type objects, it only checks the reference, not the values. In order to work with values, we need to use IEqualityComparer.
Example to Understand LINQ Contains Method in C# using Primitive Type Collection
Let us see an example to Understand LINQ Contains Method in C# using both Method and Query Syntax. In the following example, we are checking whether element 33 is present in the collection or not. The following example returns true as the data source (i.e. IntArray) contains the element 33. There is no operator called contains in Query Syntax, so we need to use Mixed Syntax.
using System; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { int[] IntArray = { 11, 22, 33, 44, 55 }; //Using Method Syntax var IsExistsMS = IntArray.Contains(33); //Using Query Syntax var IsExistsQS = (from num in IntArray select num).Contains(33); Console.WriteLine($"Is Element 33 Exist: {IsExistsMS}"); Console.ReadKey(); } } }
Output: Is Element 33 Exist: True
Example to Understand LINQ Contains Method in C# using String Type Collection
Let us see an example to Understand How to use LINQ Contains Method in C# using String type collection. For a better understanding, please have a look at the following example which shows how to use Contains Method in C# with String type collection. In the below example, we are checking whether the string collection contains the name Anurag or not. The following example will return False as the sequence or data source does not contain any element with the name Anurag.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<string> namesList = new List<string>() { "James", "Sachin", "Sourav", "Pam", "Sara" }; //Using Method Syntax //This method belongs to System.Collections.Generic namespace var IsExistsMS1 = namesList.Contains("Anurag"); //This method belongs to System.Linq namespace var IsExistsMS2 = namesList.AsEnumerable().Contains("Anurag"); //Using Query Syntax var IsExistsQS = (from num in namesList select num).Contains("Anurag"); Console.WriteLine($"Is Name Anurag Exist: {IsExistsQS}"); Console.ReadKey(); } } }
Output: Is Name Anurag Exist: False
Example to Understand LINQ Contains Method with Complex Type in C#:
Let us see an example to Understand How to use LINQ Contains Method with Complex Data Type in C# using both Method and Query Syntax. We are going to work with the following Student. So, create a class file with the name Student.cs and then copy and paste the following code into it. As you can see, the Student class has three properties such as ID, Name, and TotalMarks.
namespace LINQDemo { public class Student { public int ID { get; set; } public string Name { get; set; } public int TotalMarks { get; set; } } }
The following example returns True as the object that we pass to the Contains method exists in the data source. The point that you need to remember is while working with complex types, the Contains method checks the object reference, not the values of the object. In the below example, the object reference of the object that we passed to the Contains method is available in the data source, so in this case, it returns true.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<Student> students = new List<Student>(); var student1 = new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }; var student2 = new Student() { ID = 102, Name = "Preety", TotalMarks = 375 }; students.Add(student1); students.Add(student1); //Using Method Syntax var IsExistsMS = students.Contains(student1); //Using Query Syntax var IsExistsQS = (from num in students select num).Contains(student1); Console.WriteLine(IsExistsMS); Console.ReadKey(); } } }
Output: True
Now, let us create a new student object with the existing student object property value and pass that newly created student object to the LINQ Contains method. For a better understanding, please have a look at the following example. The following example will return False even though the values that we passed are available in the data source. This is because the default comparer which is used by the LINQ Contains Method does not check the values rather it checks the object reference and in this case, the object references are different.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<Student> students = new List<Student>() { new Student(){ID = 101, Name = "Priyanka", TotalMarks = 275 }, new Student(){ID = 102, Name = "Preety", TotalMarks = 375 } }; //Using Method Syntax var IsExistsMS = students.Contains(new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }); var student1 = new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }; //Using Query Syntax var IsExistsQS = (from num in students select num).Contains(student1); Console.WriteLine(IsExistsMS); Console.ReadKey(); } } }
Output: False
As we already discussed in our previous articles, there are four ways in which we can tell the comparer to check the value equality instead of the reference equality. Let us see all those four ways with examples.
Using IEqualityComparer Comparer with LINQ Contains Method in C#:
In this approach, we need to create a class and then we need to implement the IEqualityComparer interface and we need to provide the implementation for the Equals and GetHashCode method. So, create a class file with the name StudentComparer.cs and then copy and paste the following code into it.
using System.Collections.Generic; namespace LINQDemo { public class StudentComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { //If both object refernces are equal then return true if(object.ReferenceEquals(x, y)) { return true; } //If one of the object refernce is null then return false if (x is null || y is null) { return false; } return x.ID == y.ID && x.Name == y.Name && x.TotalMarks == y.TotalMarks; } public int GetHashCode(Student obj) { //If obj is null then return 0 if(obj is null) { return 0; } int IDHashCode = obj.ID.GetHashCode(); int NameHashCode = obj.Name == null ? 0 : obj.Name.GetHashCode(); int TotalMarksHashCode = obj.TotalMarks.GetHashCode(); return IDHashCode ^ NameHashCode ^ TotalMarksHashCode; } } }
Then you need to use the overloaded version of the Contains method which takes IEqualityComparere as a parameter. Now, create an instance of the StudentComparer and pass that instance to the Contains method as shown in the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<Student> students = new List<Student>() { new Student(){ID = 101, Name = "Priyanka", TotalMarks = 275 }, new Student(){ID = 102, Name = "Preety", TotalMarks = 375 } }; //Createing Student Comparer Instance StudentComparer studentComparer = new StudentComparer(); //Using Method Syntax var IsExistsMS = students.Contains(new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }, studentComparer); var student1 = new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }; //Using Query Syntax var IsExistsQS = (from num in students select num).Contains(student1, studentComparer); Console.WriteLine(IsExistsMS); Console.ReadKey(); } } }
Output: True
Overriding Equals() and GetHashCode() Methods within the Student Class
This is the second approach and in this approach, we need to override the Equals and GetHashCode() in the Student class. As we know, by default, any type (predefined or user-defined) .NET Framework is inherited from the Object class. That means the Student class is also inherited from the Object class. So, we can override the Equals() and GetHashCode() methods of the Object class within the Student class. So, modify the Student class as shown below.
namespace LINQDemo { public class Student { public int ID { get; set; } public string Name { get; set; } public int TotalMarks { get; set; } public override bool Equals(object obj) { //As the obj parameter type is object, so we need to //cast it to Student Type return this.ID == ((Student)obj).ID && this.Name == ((Student)obj).Name && this.TotalMarks == ((Student)obj).TotalMarks; } public override int GetHashCode() { return this.ID.GetHashCode() ^ this.Name.GetHashCode() ^ this.TotalMarks.GetHashCode(); } } }
Next, we need to modify the Main method of the Program class as shown below. Here, we need to use the overloaded version of the Contains method which does not take any parameter.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<Student> students = new List<Student>() { new Student(){ID = 101, Name = "Priyanka", TotalMarks = 275 }, new Student(){ID = 102, Name = "Preety", TotalMarks = 375 } }; //Using Method Syntax var IsExistsMS = students.Contains(new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }); var student1 = new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }; //Using Query Syntax var IsExistsQS = (from num in students select num).Contains(student1); Console.WriteLine(IsExistsMS); Console.ReadKey(); } } }
Output: True
Implementing IEquatble<T> Interface in Student Class
This is the third approach and, in this approach, we need to implement the IEquatble<T> Interface in Student Class and we need to implement the Equals Method of the IEquatble<T> Interface and we also need to override the GetHashCode method of the Object class. So, modify the Student class as shown below.
using System; namespace LINQDemo { public class Student : IEquatable<Student> { public int ID { get; set; } public string Name { get; set; } public int TotalMarks { get; set; } public bool Equals(Student obj) { return this.ID == obj.ID && this.Name == obj.Name && this.TotalMarks == obj.TotalMarks; } public override int GetHashCode() { return this.ID.GetHashCode() ^ this.Name.GetHashCode() ^ this.TotalMarks.GetHashCode(); } } }
Here, first, we implement the Equals method of the IEquatable interface and then we override the GetHashCode method of the Object class. With the above changes in place, now modify the Main Method of the Program class as shown below.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<Student> students = new List<Student>() { new Student(){ID = 101, Name = "Priyanka", TotalMarks = 275 }, new Student(){ID = 102, Name = "Preety", TotalMarks = 375 } }; //Using Method Syntax var IsExistsMS = students.Contains(new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }); var student1 = new Student() { ID = 101, Name = "Priyanka", TotalMarks = 275 }; //Using Query Syntax var IsExistsQS = (from num in students select num).Contains(student1); Console.WriteLine(IsExistsMS); Console.ReadKey(); } } }
Output: True
In the next article, I am going to discuss LINQ Deferred Execution vs Immediate Execution in C# with Examples. In this article, I try to explain the LINQ Contains Method in C# with Examples. I hope you understood the need and use of the LINQ Contains Method in C# with Examples.
I’m not seeing the 4th way