
Using LINQ Union to combine data
Author - Abdul Rahman (Bhai)
LINQ
26 Articles
Table of Contents
What we gonna do?
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.
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.
Why we gonna do?
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
How we gonna do?
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
List<int> list = new() { 1, 2, 3, 4, 5 };
List<int> anotherList = new() { 4, 5, 6 };
//Method Syntax
List<int> result = list
.Union(anotherList)
.ToList();
//Query Syntax
List<int> result = (from number in list select number)
.Union(anotherList)
.ToList();
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.
public class ProductComparer : EqualityComparer<Product>
{
public override bool Equals(Product? product, Product? anotherProduct)
{
return (product?.Id == anotherProduct?.Id &&
product?.Name == anotherProduct?.Name &&
product?.Price == anotherProduct?.Price &&
product?.Color == anotherProduct?.Color &&
product?.Size == anotherProduct?.Size);
}
public override int GetHashCode([DisallowNull] Product product)
{
return $"{product.Id}{product.Name}{product.Price}{product.Color}{product.Size}".GetHashCode();
}
}
List<Product> products = GetProducts();
List<Product> anotherProducts = GetProducts();
ProductComparer productComparer = new();
//Method Syntax
List<Product> result = products
.Union(anotherProducts, productComparer)
.ToList();
//Query Syntax
List<Product> result = (from product in products select product)
.Union(anotherProducts, productComparer)
.ToList();
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.
List<Product> products = GetProducts();
List<Product> anotherProducts = GetProducts();
//Method Syntax
List<Product> result = products
.UnionBy(anotherProducts, product => product.Id)
.ToList();
//Query Syntax
List<Product> result = (from product in products select product)
.UnionBy(anotherProducts, product => product.Id)
.ToList();
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.