Joining two collections using the C# Concat LINQ operator

What if you want to join two sequences of the same type into one sequence? It couldn’t be easier with the LINQ Concat() operator.

Data structure:

string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers"
, "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears"
, "Deep Purple", "KISS"};

Say you’d like to get the first and the last 5 elements of this sequence and build a single sequence. The following LINQ statement will do the trick:

IEnumerable<string> selectedItems = bands.Take(5).Concat(bands.Reverse().Take(5));
foreach (string item in selectedItems)
{
	Console.WriteLine(item);
}

Concat operator output

You can view all LINQ-related posts on this blog here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.