BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 3.5+

LINQ Concatenation

The eleventh part of the LINQ to Objects tutorial describes concatenation using language-integrated query (LINQ). LINQ provides a single concatenation operator that combines all of the items from two sequences into a single collection.

Concatenation

When using LINQ, concatenation is the act of combining the elements from two sequences into one larger set of data. LINQ has one standard query operator that performs concatenation, which is named Concat. The operator expects one argument to be provided. This parameter must contain a sequence that implements the IEnumerable<T> interface and the type of the elements in the collection must match that of the sequence that the Concat extension method is executed against.

As with many other LINQ operators, Concat uses deferred execution. The returned object contains all of the information required to build a new enumerable collection but the new list is not generated until the data is first read. The generated sequence contains all items from both source collections, including duplicated data.

The code below shows the concatenation of two string arrays.

string[] fruit = new string[] { "Apple", "Orange", "Grape" };
string[] veg = new string[] { "Broccoli", "Carrot", "Potato" };

var fruitAndVeg = fruit.Concat(veg);

foreach (var food in fruitAndVeg)
{
    Console.WriteLine(food);
}

/*

Apple
Orange
Grape
Broccoli
Carrot
Potato

*/

The purpose of the concatenation method is to combine sequences so that they can be used as one. For example, the following sample uses two LINQ operators to combine the two arrays and sort the results.

var fruitAndVeg = fruit.Concat(veg).OrderBy(s => s);

foreach (var food in fruitAndVeg)
{
    Console.WriteLine(food);
}

/*

Apple
Broccoli
Carrot
Grape
Orange
Potato

*/
9 September 2010