
Using LINQ Concat 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 Concat in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ Union to combine data.
When working with two collections, we can combine them using LINQ Concat() method. This will combine two collections and gives a single collection with duplicates.
Why we gonna do?
LINQ Concat() is used to answer questions about collection such as
- Combining multiple data set from different sources for analysis
- Git merge and combine files with changes from both commits
- Append lines to files
How we gonna do?
Using LINQ Concat 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
.Concat(anotherList)
.ToList();
//Query Syntax
List<int> result = (from number in list select number)
.Concat(anotherList)
.ToList();
Using LINQ Concat to combine with Equality Comparer
So, combining primitive data types with Concat() is easy and straight forward. The same goes with objects. There is no need for comparer as Concat() is going to simply combine without comparing.
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
.Concat(anotherProducts, productComparer)
.ToList();
//Query Syntax
List<Product> result = (from product in products select product)
.Concat(anotherProducts, productComparer)
.ToList();
Summary
In this article we learn't how to combine data between collections using Concat. This can be used to combine items between collection and return a unified collection with duplicates. All these can be used with any IEnumerable or IQueryable types.