What is the purpose of "Concat" method in LINQ?
The Concat
method in LINQ serves the purpose of combining two or more sequences or collections into a single sequence. It allows you to concatenate, or join together, the elements from multiple sources, creating a new sequence that contains all the items from each source in the specified order. This can be valuable when you need to merge data from different collections or when you want to create a larger collection from smaller ones.
Here's the syntax of the Concat
method in LINQ:
IEnumerable<TSource> result = sequence1.Concat(sequence2);
-
'sequence1' and 'sequence2' represent the collections or sequences that you want to concatenate.
Here's a complete source code example to illustrate the usage of the Concat
method along with its output:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create two lists of integers
List list1 = new List { 1, 2, 3 };
List list2 = new List { 4, 5, 6 };
// Use LINQ to concatenate the two lists
IEnumerable concatenatedList = list1.Concat(list2);
Console.WriteLine("List 1: " + string.Join(", ", list1));
Console.WriteLine("List 2: " + string.Join(", ", list2));
Console.WriteLine("Concatenated List: " + string.Join(", ", concatenatedList));
}
}
Output:
List 1: 1, 2, 3
List 2: 4, 5, 6
Concatenated List: 1, 2, 3, 4, 5, 6
In this example, we have two lists of integers, list1
and list2
. Using the Concat
method in LINQ, we merge these two lists into a single sequence called concatenatedList.
The result is a new sequence that contains all the elements from both list1
and list2
. As demonstrated in the output, the Concat
method effectively combines the data from the two lists, creating a larger and concatenated list of integers.
So, the Concat
method in LINQ is a valuable tool for merging data from multiple sources into a single sequence, simplifying the process of working with combined or aggregated data.