Using LINQ Concat to combine data

Using LINQ Concat to combine data

linq

23 Articles

Improve

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.

Table of Contents

  1. Introduction
  2. Using LINQ Concat to combine primitive types
  3. Using LINQ Concat to combine with Equality Comparer
  4. Summary

Introduction

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.

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

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

Code Sample - LINQ Concat Primitive Types

Demo - LINQ Concat Clause Demo

Let's try LINQ Concat with integer type

  1. Enter number and add it to respective sequence
  2. For demo purpose I have restricted sequence length to 3
  3. Click on Concat Button to view the result
  4. Click on reset to try other combination

Combined with duplicates :

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.

Code Sample - LINQ Concat Product Comparer

Code Sample - LINQ Concat With Product Comparer

Demo - LINQ Concat Clause with Objects Demo

Let's try LINQ Concat with Comparer

  • We have Product class with following properties - Id, Name
  • The tables are loaded with two product collection.
  • Click on Concat Button to view the result.
  • Unlike previous demo, here we use ProductComparer to compare objects based on their property values. So they will be equal irrespective of reference.
  • Click on reset to try other combination
Id Name
3 Shirt
4 Shirt
5 Shirt
6 Shirt
Id Name
1 Shirt
2 Shirt
3 Shirt
4 Shirt

Combined Products with duplicates :

Id Name

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.

  • Linq
  • Concat
  • Concatenate
  • Combine
  • Duplicate