LINQ Contains Method in C#

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 before proceeding to this article where we discussed the Linq Any Operator in C# with some different types of examples.

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 return false. There Contains method in C# is implemented in two different namespaces as shown in the below image.

Linq Contains Method in C#

The Contains method belongs to System.Collections.Generic namespace takes one element as an input parameter and if that element present in the data source then it returns true else false.

There are two overloaded versions available for Contains method belongs to System.Linq namespace and of the method takes IEqualityComparer.

Note: This 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.

Example1:

The following example returns true as the data source (i.e. IntArray) contains the element 33.

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(IsExistsMS);
            Console.ReadKey();
        }
    }
}

Output: True

Example2:

The following example returns 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(IsExistsQS);
            Console.ReadKey();
        }
    }
}

Output: False

Working with Complex Type:

We are going to work with the following Student and Subject class. So, create a class file with the name Student.cs and then copy and paste the following code.

namespace LINQDemo
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int TotalMarks { get; set; }
    }
}
Example3:

The following example returns True as the object that we pass to the Contains method is exists in the data source.

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

Note: While working with complex type, the Contains method checks the object reference, not the values of the object. In the above example, the object reference of the object we passed is available in the data source, so it returns true.

Example4:

The following example returns false even though the values that we passed is available in the data source. This is because the Linq Contains Method in C# 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

If you want to check the values rather than the reference then you need to create a class and need to implement the IEqualityComparere interface. Then you need to use the overloaded version of Contains method which takes IEqualityComparere as a parameter.

Creating StudentComparer class:

Create a class file with the name StudentComparer and then copy and paste the following code in 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;
        }
    }
}
Example5:

Now pass the StudentComparer instance to the contains method 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 }
                        };

            //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

In the next article, I am going to discuss Linq GroupBy Operators in C# with examples. In this article, I try to explain the Linq Contains Method in C# with some examples. I hope you understood the need and use of Linq Contains Method in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *