LINQ Intersect Operator

C#  LINQ  C#  linq 

LINQ Intersect operator is used to find common elements between two sequences (collections). Intersect opertor comes under Set operators category in LINQ Query operators.

For example, we have two collections A = { 1, 2, 3 } and B = { 3, 4, 5 }. Intersect operator will find common elements in both sequences. { 3 } element is common in both sequences. So Intersect operator only shows one element in the resulting sequence { 3 }.

Intersect operator is only available in Method Syntax and not available in Query Syntax.

Below is the syntax of Intersect operator:

public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);

There are two overload methods. First one only takes the second sequence and second one takes one additiona parameter IEqualityComparer which is used for comparing custom Types.

C# LINQ Intersect Example

string[] employeesInDeptA = { "Asutosh", "Kapil", "Sumit", "Rajat" };
string[] employeesInDeptB = { "Preeti", "Sumit", "Kanupriya", "Kapil" };

var result = employeesInDeptA.Intersect(employeesInDeptB);

Console.WriteLine("Common Employees in Department A and B:");
foreach (var item in result)
{
    Console.WriteLine(item);
}

Try It

Common Employees in Department A and B:
Kapil
Sumit

In the above example, we have two department of employees A and B. We need to find those employees who are working in both departments. We call Intersect operator method on employeesInDeptA and pass employeesInDeptB variable as a parameter. In the result we got employees names "Kapil" and "Sumit" which are common in both sequences.

Intersect Example with IEqualityComparer

By default, Intersect operator can not compare custom types. To remove this shortcomings, we have to use second overload method of Intersect operator. In this method, we can use IEqualityComparer interface which can be used for comparing custom types. Below is the example:

internal class Employee
{
    public string ID { get; set; }
    public string Name { get; set; }
}

internal class EmployeeNameComparer : IEqualityComparer<Employee>
{
    public bool Equals(Employee x, Employee y)
    {
        if(string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
        return false;
    }

    public int GetHashCode(Employee obj)
    {
        return obj.Name.GetHashCode();
    }
}

public static void Main(string[] args)
{
    List<Employee> employeesInDeptA = new List<Employee>();
    List<Employee> employeesInDeptB = new List<Employee>();

    employeesInDeptA.Add(new Employee
    {
        ID = "A1",
        Name = "Asutosh"
    });
    employeesInDeptA.Add(new Employee
    {
        ID = "A2",
        Name = "Kapil"
    });
    employeesInDeptA.Add(new Employee
    {
        ID = "A3",
        Name = "Sumit"
    });
    employeesInDeptA.Add(new Employee
    {
        ID = "A4",
        Name = "Rajat"
    });

    employeesInDeptB.Add(new Employee
    {
        ID = "B1",
        Name = "Preeti"
    });
    employeesInDeptB.Add(new Employee
    {
        ID = "B2",
        Name = "Sumit"
    });
    employeesInDeptB.Add(new Employee
    {
        ID = "B3",
        Name = "Kanupriya"
    });
    employeesInDeptB.Add(new Employee
    {
        ID = "B4",
        Name = "Kapil"
    });

    var result = employeesInDeptA.Intersect(employeesInDeptB, new EmployeeNameComparer());

    Console.WriteLine("Common Employees in Department A and B:");
    foreach (var item in result)
    {
        Console.WriteLine(item.ID + " " +  item.Name);
    }
}

Try It

Common Employees in Department A and B:
A2 Kapil
A3 Sumit

In the above example, we have create a new class EmployeeNameComparer which implements IEqualityComparer<Employee>. This class is used with Intersect operator for comparing custom Employee types.

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.