Home
C#
Reverse Extension Method
This page was last reviewed on Apr 5, 2023.
Dot Net Perls
Reverse. Elements can be reversed in many ways. One way applies the Reverse extension method for a declarative, clear syntax. The Reverse method acts upon many collection types.
Extension
With this extension method, we receive the elements in the opposite order. Reverse can be used on lists, arrays and IEnumerable things. It is useful, but not perfect.
IEnumerable
First example. We invoke the Reverse extension method from the System.Linq namespace. The program includes the System.Linq namespace at the top—this is important.
Tip The Reverse extension method is not defined on the array type. It is an extension, not instance, method.
Info Reverse() is from System.Linq and can act upon arrays. This program writes the opposite element order in the array to the screen.
Console.WriteLine
using System; using System.Linq; // Create an array. int[] array = { 1, 2, 4 }; // Call reverse extension method on the array. var reverse = array.Reverse(); // Write contents of array to screen. foreach (int value in reverse) { Console.WriteLine(value); }
4 2 1
Reverse, expression. A key benefit to Reverse() here is that it can be called directly upon a query expression. So we do not need to convert anything to an array first.
Detail We use a query expression to get all the numbers greater than or equal to 10, and then reverse the results.
using System; using System.Linq; int[] array = { 1, 0, 20, 40, -2 }; // Use Reverse as part of a query expression. var higherNumbers = (from number in array where number >= 10 select number).Reverse(); // Display results. foreach (int value in higherNumbers) { Console.WriteLine("GREATER THAN 10 REVERSED: {0}", value); }
GREATER THAN 10 REVERSED: 40 GREATER THAN 10 REVERSED: 20
Performance. The Reverse extension method will likely have worse performance in many cases than other methods. This is because there is an iterator used in the LINQ method.
Detail LINQ requires more allocations and in the end results in worse performance.
Array.Reverse. To achieve better performance, it would be possible to use the Array.Reverse method, or even use imperative statements and loops.
Array.Reverse
Array
Also Typically, LINQ methods will degrade performance on low-level value type collections.
A review. The Reverse extension method is effective. But it may not be ideal for all programs. The declarative, function-based syntax of Reverse is short but not optimally fast.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 5, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.