Introduction
When it is necessary to process an array in normal order, we can use the statement foreach.
But if we want to process the array in reverse order: from the last array's element to the first (0) element, we have a problem. Sure, we can use a loop for (in reverse order) or call method Array.Reverse() and reverse elements of the original array. Now we can suggest an additional way to get reverse processing of the array with the help of generics and yield.
Sample process (output to console) int and string array in "normal" and "reverse" orders.
using System;
class Program
{
static void Main()
{
SampleReverse();
}
static void SampleReverse()
{
int[] intArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string[] strArray = new string[] { "zero", "one", "two", "three", "four", "five" };
DisplayArray(intArray);
DisplayArray(Reverse(intArray));
DisplayArray(Reverse(strArray));
}
static T[] Reverse<T>(T[] array)
{
T[] reversedArray = new T[array.Length];
int j = array.Length - 1;
for (int i = 0; i < array.Length; i++)
{
reversedArray[i] = array[j];
j--;
}
return reversedArray;
}
static void DisplayArray<T>(T[] array)
{
Console.WriteLine(string.Join(", ", array));
}
}
We cannot methods DisplayArray() and ReverseArray() can receive an array of any elements.
It is implemented with the help of c# generics.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Example usage of DisplayArray method
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
DisplayArray(numbers);
}
static void DisplayArray<T>(IEnumerable<T> displayedArray)
{
Console.WriteLine();
foreach (T item in displayedArray)
{
Console.Write("{0} ", item);
}
}
}
More interesting how to implement the method Reverse() without creating of new array or changing the original array.
We use statement yield.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Example usage of the Reverse method
int[] numbers = { 1, 2, 3, 4, 5 };
IEnumerable<int> reversedNumbers = Reverse(numbers);
foreach (var number in reversedNumbers)
{
Console.Write(number + " "); // Output: 5 4 3 2 1
}
}
static IEnumerable<T> Reverse<T>(T[] originalArray)
{
for (int i = originalArray.Length - 1; i >= 0; i--)
{
yield return originalArray[i];
}
}
}
Console
Reference