Linq Concat Method in C#

The Concat method in LINQ is a powerful tool that allows you to combine two or more collections of data in C#. This method is used to concatenate two or more sequences into a single sequence. In this lesson, we’ll explore the Concat method in depth, including how to use it and provide examples and tips to help you master this powerful tool.

The Concat method is part of the System.Linq namespace in C#. The basic syntax for using this method is:

var concatenatedData = collection1.Concat(collection2);

Here, collection1 and collection2 are the collections of data you want to combine. The Concat method returns a new collection that contains all the elements of the first collection followed by all the elements of the second collection.

One important thing to note is that the Concat method does not modify the original collections. Instead, it creates a new collection that contains all the elements of the original collections.

Here are some tips and examples for using the Concat method in LINQ:

Combining multiple collections:

You can use the Concat method to combine multiple collections of data. For example, if you have three collections collection1, collection2, and collection3, you can combine them like this:

var concatenatedData = collection1.Concat(collection2).Concat(collection3);

This will create a new collection that contains all the elements of collection1, collection2, and collection3.

Combining collections of different types:

You can use the Concat method to combine collections of different types as long as they have a common base class or interface. For example, if you have a collection of Person objects and a collection of Employee objects, you can combine them like this:

var concatenatedData = people.Concat(employees);

Here, both Person and Employee classes have a common base class or interface, such as object or IPerson.

Using Concat with other LINQ methods:

You can combine the Concat method with other LINQ methods to create more complex queries. For example, you can use Concat with Where to combine two collections and then filter the result based on a condition, like this:

var filteredData = collection1.Concat(collection2).Where(x => x.PropertyName == "some value");

This will create a new collection that contains all the elements of collection1 and collection2 that have a PropertyName value of “some value”.

In conclusion, the Concat method in LINQ is a powerful tool that allows you to combine two or more collections of data in C#. By mastering this method, you can easily concatenate your data and create more complex queries using LINQ.