Updated April 5, 2023
Introduction to LINQ Union
LINQ Union is used to retrieve the distinct elements between two collections/ sequences; it combines two or more collections of elements and finally returns the unique elements as a result. LINQ Union is an extension method that requires two collections to combine the two collections and returns the distinct elements from both collections. LINQ Union supports only method syntax; it does not support the query syntax. The Union method presents in both the classes Queryable class and Enumerable class.
Syntax:
Let’s see the LINQ Union method syntax as follows,
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);
If you are working with complex types of union collection, then you must make use of the IEqualityComparer interface to get an accurate result; otherwise, you will get only the incorrect result.
How does Union work in LINQ?
In LINQ Union method it only supports the method syntax; the query syntax will not be available in the union method. The Queryable and Enumerable classes will be acceptable in the union method. The Union operator or method is mainly used to combine the multiple collections into a single distinct collection; it returns only the unique elements; as a result, it removes the duplicate values from the collection. Let’s see one example as follows.
For Example,
Collection X= {20, 40, 60, 80, 100}
Collection Y= {20, 40, 70}
var _result = X.Union(Y);
The result is = {20, 40, 60, 70, 80, 100} in this resultant collection, the elements 20 and 40 appear in both the collection, so in the result, it returns only once because unique elements are only displayed it eliminates the duplications. Let’s see the working flow of the unique method as follows,
static public void Main()
{
string[] Department1 = { "JAVA", "DOTNET", "PHYTHON", "ANDROID" };
string[]Department2 = { "JAVA", "ANDROID", "DESIGNING" };
var unionResult = Department1.Union(Department2);
foreach (var items in unionResult)
{
Console.WriteLine(items);
}
}
In the above coding, there are two collections of elements Courses_1 and Courses_2 which contains the name of the courses as follows,
string[]Department1 = { "JAVA", "DOTNET", "PHYTHON", "ANDROID" };
string[]Department2 = { "JAVA", "ANDROID", "DESIGNING" };
From this, we have to return only the unique elements from both the collections it removes the duplications from both collections, to get all the elements uniquely, we need to go with the Union () method,
var unionResult = Department1.Union(Department2);
It returns only the unique elements from the collection, in which it removes the repeated elements present in the collection it returns only once; let’s check the result here below,
Result is {"JAVA", "DOTNET","DESIGNING", "PHYTHON", "ANDROID"};
Usage of IEqualityComparer Interface
Here we introduce the IEqualityComparer Interface for the union method because the union method can’t be able to differentiate whether the two types are equal; it does not work with complex types of collection, so it returns the only incorrect result. For this purpose, we have to build a new comparer class to implement IEqualityComparer Interface to get an accurate result. IEqualityComparer Interface has two different methods, GetHashCode and Equals methods; we need to implement both methods compulsory. Let’s see one example for IEqualityComparer interface and lets us assume the Book Class contains BookID and BookName,
class BookComparer : IEqualityComparer<Book>
{
public bool Equals(Book x, Book y)
{
if (x.BookID == y.BookID && x.BookName.ToLower() == y. BookName.ToLower())
return true;
return false;
}
public int GetHashCode(Student obj)
{
return obj. BookID.GetHashCode();
}
}
Now can send the BookComparer class in the Union extension method to get the accurate results.
List<BookClass> BookList_1 = new List< BookClass >();
BookList _1.Add(new BookClass { BookID = 1001, BookName = "The Writer" });
BookList _1.Add(new BookClass { BookID = 1002, BookName = " Success " });
BookList _1.Add(new BookClass { BookID = 1003, BookName = "Life Secret " });
List< BookClass > BookList _2 = new List< BookClass >();
BookList _2.Add(new BookClass { BookID = 1002, BookName = "Success" });
BookList _3.Add(new BookClass { BookID = 1005, BookName = "Team Lead " });
var _resultUnion = BookList _1.Union(BookList _2, new BookComparer());
foreach (BookClass res in _resultUnion)
Console.WriteLine(res. BookName);
The result will be” The Writer, Success, Life Secret, Team Lead,” it returns only the unique elements from the collection, in which it removes the repeated elements.
Example
When working with complex types of union collection, then you must make use of the IEqualityComparer interface to get an accurate result. IEqualityComparer Interface has two different methods, GetHashCode and Equals methods; we need to implement both methods compulsory. Let’s see one sample program,
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LINQUnion
{
class Linq_Union
{
internal class DoctorClass
{
public int DoctorID { get; set; }
public string DoctorName { get; set; }
}
// UNION Operator with IEqualityComparer
internal class DoctorComparer : IEqualityComparer<DoctorClass>
{
public bool Equals(DoctorClass a, DoctorClass b)
{ if(a.DoctorID==b.DoctorID&&b.DoctorName.ToLower()==b.DoctorName.ToLower())
{
return true;
}
return false;
}
public int GetHashCode(DoctorClass obj)
{
return obj.DoctorID.GetHashCode();
}
}
public class Program
{
public static void Main(string[] args)
{
List<DoctorClass> DoctorList_1 = new List<DoctorClass>();
DoctorList_1.Add(new DoctorClass { DoctorID = 1001, DoctorName = "Smith" });
DoctorList_1.Add(new DoctorClass { DoctorID = 1002, DoctorName = "Rio" });
DoctorList_1.Add(new DoctorClass { DoctorID = 1003, DoctorName = "Dev" });
DoctorList_1.Add(new DoctorClass { DoctorID = 1004, DoctorName = "Jack" });
DoctorList_1.Add(new DoctorClass { DoctorID = 1005, DoctorName = "Ricky" });
List<DoctorClass> DoctorList_2 = new List<DoctorClass>();
DoctorList_2.Add(new DoctorClass { DoctorID = 1002, DoctorName = "Rio" });
DoctorList_2.Add(new DoctorClass { DoctorID = 1003, DoctorName = "Dev" });
DoctorList_2.Add(new DoctorClass { DoctorID = 1007, DoctorName = "Peter" });
DoctorList_2.Add(new DoctorClass { DoctorID = 1009, DoctorName = "Raj" });
DoctorList_2.Add(new DoctorClass { DoctorID = 1001, DoctorName = "Smith" });
var _resultUnion = DoctorList_1.Union(DoctorList_2, new DoctorComparer());
Console.WriteLine("USING LINQ-UNION WITH IEqualityComparer");
Console.WriteLine("---------------------------------------\n");
Console.WriteLine("List of Unique Doctor-Names\n");
foreach (DoctorClass val in _resultUnion)
Console.WriteLine(val.DoctorName);
Console.ReadLine();
}
}
}
}
Output:
Conclusion
The article LINQ Union essentially used to combine the collection of elements and returns distinct elements; as a result, when working on complex types of huge data, we need to implement the IEqualityComparer Interface. I hope the article helps out without any doubt by seeing the examples programmatically.
Recommended Articles
This is a guide to LINQ Union. Here we discuss the Introduction, syntax, How Union works in LINQ along with Examples and code implementation. You may also have a look at the following articles to learn more –