Updated April 18, 2023
Introduction to LINQ Intersect
LINQ Intersect is an operator which comes under the Set Operators’ category. The Intersect operator is used to find the common elements in the collections, it requires two collections. LINQ Intersect returns the new sequence of an element which is the element that is common in both collections. It will be available only in Method syntax.
Syntax:
Here the syntax for LINQ_Intersect is as follows,
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 overloaded methods for Intersect method, the first method takes only the second sequence of elements whereas the second method takes the extra additional parameter the interface called IEqualityComparer which is used to comparing the custom types when a complex problem occurs.
How Intersect works in LINQ?
LINQ Intersect operator is used to find the common elements between the two collections. Both of the collections must have the same data type, intersect operator which returns the set intersection it describes that the common elements present in two collections. The essential thing is the intersect method requires two collections, from that collection it returns a new collection of elements which includes the common elements that are present in that collection. Let’s see one example for better understanding,
Consider A= {10, 20, 30} and B= {30, 40, 50} the intersect operator finds the common elements from both sequences A and B respectively, so the final result will be {30} the common element in both sequences is only the number 30.
Let us see the below coding for LINQ-Intersect operation as follows,
string[] Customers_Of_Company_A = { "Tina", "Amit", "Jack", "Ritu" };
string[] Customers_Of_Company_B = { "Jack", "Sumit", "Joe", "Alen" };
var intersectResult = Customers_Of_ Company_A.Intersect(Customers_Of_Company_B);
Console.WriteLine("Common Customers from both the companies are:");
foreach (var names in intersectResult)
{
Console.WriteLine(names);
}
In the above coding, we have two collections of customer names from two companies Customers_Of_Company_A and Customers_Of_Company_B respectively. By using Intersect we have to find the customers who work in both the companies with the same name, here we use the intersect operator on Customers_Of_Company_A and pass the second company name Customers_Of_Company_B as a parameter.
var intersectResult = Customers_Of_ Company_A.Intersect(Customers_Of_Company_B);
By using this code we will get the result. Finally, we will get the result “Jack” which exists common in both the companies.
Example for IEqualityComparer for Intersect
LINQ Intersect method we go with the IEqualityComparer Interface because when we working on the collections with complex types it leads to the incorrect result so we proceed with this method. The IEqualityComparer has two different methods for the implementation they are GetHashCode() and Equals(). In the below example, we will see the IEqualityComparer Interface programmatically.
Examples
The essential thing is the intersect method requires two collections, from that collection it returns a new collection of elements which includes the common elements that are present in those collections.
Example #1
Code:
using System;
using System. Linq;
class LINQ_Intersect
{
static public void Main()
{ // two sequences
char[] sequence1 = {'A', 'S', 'D','F', 'V', 'W'};
char[] sequence2 = {'E', 'R', 'T','S', 'H', 'K'};
// to get the common elements use the intersection of the given sequence
// here we using the Intersect function
var resultIntersect = sequence1.Intersect(sequence2);
Console.WriteLine("Common Elements are: ");
foreach (var num in resultIntersect)
{
Console.WriteLine(num);
}
Console.ReadLine();
}
}
Output:
In the LINQ Intersect method we go with the IEqualityComparer Interface because when we working on the collections with complex types it leads to the incorrect result so we proceed with this method. The IEqualityComparer has two different methods for the implementation they are GetHashCode() and Equals() let’s see the following program for better understanding.
Example #2
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LinqIntersect
{
internal class StudentDetails_Class
{
public int Student_ID { get; set; }
public string Student_Name { get; set; }
}
//USING INTERSECT WITH IEqualityComparer
internal class StudentNameComparer : IEqualityComparer<StudentDetails_Class>
{
public bool Equals(StudentDetails_Class a, StudentDetails_Class b)
{
if(string.Equals(a.Student_Name, b.Student_Name, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
public int GetHashCode(StudentDetails_Class obj)
{
return obj.Student_Name.GetHashCode();
}
}
public class Program
{
public static void Main(string[] args)
{
List<StudentDetails_Class> MBA_Dept = new List<StudentDetails_Class>();
List<StudentDetails_Class> MCA_Dept = new List<StudentDetails_Class>();
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1001, Student_Name = "Smith" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1002, Student_Name = "Rio" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1003, Student_Name = "Dev" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1007, Student_Name = "Ritu" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1008, Student_Name = "David" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1009, Student_Name = "Rio" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1010, Student_Name = "Jack" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1004, Student_Name = "Ponting" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1005, Student_Name = "Dev" });
MBA_Dept.Add(new StudentDetails_Class { Student_ID = 1006, Student_Name = "Sarvan" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2001, Student_Name = "Elan" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2002, Student_Name = "Ricky" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2007, Student_Name = "Smith" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2008, Student_Name = "Dev" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2009, Student_Name = "Rio" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2003, Student_Name = "Dev" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2004, Student_Name = "Ram" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2005, Student_Name = "Dev" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2006, Student_Name = "Shasha" });
MCA_Dept.Add(new StudentDetails_Class { Student_ID = 2010, Student_Name = "Mithun" });
var result_Intersect = MBA_Dept.Intersect(MCA_Dept, new StudentNameComparer());
Console.WriteLine("\n\nUSING INTERSECT WITH IEqualityComparer");
Console.WriteLine("--------------------------------------\n");
Console.WriteLine("Common Student Names from Department MBA and MCA:\n");
foreach (var get_student in result_Intersect)
{
Console.WriteLine(get_student.Student_ID+"\t"+get_student.Student_Name);
}
Console.ReadLine();
}
}
}
In the above code to retrieve the exact result for complex types of problems we go with IEqualityComparer in that code, we created a new class StudentNameComparer which implements the IEqualityComparer<StudentDetails_Class>. That class is used with the intersect operator for comparing the custom student types to retrieve the common elements from two collections to get the correct result.
Output:
Conclusion
In this article, we learned about the LINQ-Intersect method which is used to find the common elements from the collections. To achieve with complex types of data we explained the IEqualityComparer Interface with examples programmatically. Hope the article helps you with a better understanding.
Recommended Articles
This is a guide to LINQ Intersect. Here we discuss the Introduction, Syntax, How Intersect works in LINQ? and examples with code implementation for better understanding. You may also have a look at the following articles to learn more –