Joining two collections using the C# Concat LINQ operator
May 27, 2014 Leave a comment
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); }
You can view all LINQ-related posts on this blog here.