C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ConsoleC# program that uses Reverse extension method
using System;
using System.Linq;
class Program
{
static void Main()
{
// 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);
}
}
}
Output
4
2
1
Program: We use a query expression to get all the numbers greater than or equal to 10, and then reverse the results.
C# program that uses Reverse, query expression
using System;
using System.Linq;
class Program
{
static void Main()
{
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);
}
}
}
Output
GREATER THAN 10 REVERSED: 40
GREATER THAN 10 REVERSED: 20
Allocations: LINQ requires more allocations and in the end results in worse performance.
Also: Typically, LINQ methods will degrade performance on low-level value type collections.