Free Web Development Online Tutorials, Learn to Code
Learn LINQ with C#, Language Integrated query with different Data Source

How to use LINQ Union, Intersect, Except

Using Union, Intersect, Except In LINQ

Union is an extension method to merge two collections, After merging new collection holds the distinct values from both the collections

Let's look at some example

IEnumerable<string> countries = new List<string> { "India", "USA", "UK", "Canada", "Australia","UAE" };
IEnumerable<string> countries1 = new List<string> { "Srilanka", "Germany", "France", "Singapore", "UAE" };
           
IEnumerable<string> allCountries = countries.Union(countries1);

Now in above two lists we have "UAE" repeated, but after union in new list there will be only one "UAE".
Let's check the list

foreach (var c in allCountries)
{
    Console.WriteLine(c);
}

Now if you have complex object type, where you want to use Union, then the above example may not give you right result, you need to use IEqualityComparer

How to use LINQ Union with IEqualityComparer

Here we implement IEqualityComparer for complex object type Teacher

class TeacherComparer : IEqualityComparer<Teacher> {
public bool Equals(Teacher t, Teacher t1)
{
if (t.teacherId == t1.teacherId && t.City.ToLower() == t1.City.ToLower())
return true;
return false;
}
public int GetHashCode(Teacher obj)
    {
        return obj.teacherId.GetHashCode();
    }
}

Let's create two list of complex object type Teacher with some data

IList<Teacher> teacherList1 = new List<Teacher>() {
new Teacher() { teacherId = 1, FullName = "Venkatesh", City = "Bangalore"} ,
new Teacher() { teacherId = 2, FullName = "Arunava", City = "Kolkata"} ,
new Teacher() { teacherId = 3, FullName = "Akansha", City = "Kolkata"} ,
new Teacher() { teacherId = 5, FullName = "Simon" , City = "New Jersy" }
};

IList<Teacher> teacherList2 = new List<Teacher>() { new Teacher() { teacherId = 6, FullName = "Monica", City = "Kolkata"} , new Teacher() { teacherId = 2, FullName = "Arunava", City = "Kolkata"} , new Teacher() { teacherId = 7, FullName = "Janet", City = "New Jersy"} , new Teacher() { teacherId = 8, FullName = "Mellisa" , City = "New York" } };

Now we use the above IEqualityComparer class TeacherComparer, we pass the TeacherComparer class in Union extension method.

var allTeachers = teacherList1.Union(teacherList2, new TeacherComparer());
foreach (var c in allTeachers)
{
    Console.WriteLine(string.Format("{0}-{1}", c.FullName, c.City));
}
Comment
Name
Email
Website
Subscribe
 
Learn LINQ .Net

LINQ Union Intersect Except Example- Union in LINQ Query

linq Interview Questions Answers

LINQ C# examples | Join Asp.net MVC Course