Reversing a sequence using the Reverse operator in .NET LINQ
June 3, 2014 Leave a comment
Reversing the order of a sequence with LINQ is extremely simple: just use the Reverse() operator.
Example 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"};
You can use the Reverse operator as follows:
IEnumerable<string> bandsReversed = bands.Reverse(); foreach (string item in bandsReversed) { Console.WriteLine(item); }
…which will print the above array in reverse order, i.e. starting with KISS and finishing with ACDC.
You can view all LINQ-related posts on this blog here.