Using LINQ Union to combine data
LINQ
26 Articles
In this article, let's learn about how to use Union in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ Intersect to Find Common data.
Table of Contents
- Introduction
- Using LINQ Union to combine primitive types
- Using LINQ Union to combine with Equality Comparer
- Using LINQ Union By to combine objects
- Summary
Introduction
When working with two collections, we can combine them using LINQ Union() method. This will combine two collections and gives a single collection with out any duplicates.
LINQ Union() is used to answer questions about collection such as
- Git merge and combine files without duplicates
- Combine customers who have participated in specific sale
Using LINQ Union to combine primitive types
Primitive data types like int, decimal, string, etc can just compare the values against other value in the collection
Code Sample - LINQ Union Primitive Types
Using LINQ Union to combine with Equality Comparer
So, combining primitive data types with Union() is easy and straight forward, but with objects by default it's going to work by comparing object references. But in most cases we want to make comparison based on one or more properties in the object. To do that we need to start by creating EqualityComparer<T> class.
- Create a ProductComparer class that inherits from EqualityComparer<Product> class.
- Override Equals(Product 1, Product 2) method.
- Write the conditions to check equality and return true if both matches.
- Also override GetHashCode() method and return unique value for every single object.
Code Sample - LINQ Union Product Comparer
Code Sample - LINQ Union With Product Comparer
Using LINQ Union By to combine objects
Starting .NET 6, Microsoft added UnionBy() which is similar to Union in functionality but with an simplification that we don't need to use a comparer class. We can use Key Expression to combine items.
Code Sample - LINQ Union By Object Types
Summary
In this article we learn't how to combine data between collections using Union and UnionBy. This can be used to combine items between collection and return a unified collection without duplicates. All these can be used with any IEnumerable or IQueryable types.