December 2007
Intermediate to advanced
896 pages
19h 57m
English
You want an efficient method to swap two elements that exist within a single array.
Use the generic SwapElementsInArray<T> method that extends the generic Array type:
public static void SwapElementsInArray<T>(this T[] theArray, int index1, int
index2)
{
T tempHolder = theArray[index1];
theArray[index1] = theArray[index2];
theArray[index2] = tempHolder;
}There is no specific method in the .NET Framework that allows you to swap only two specific elements within an array. The SwapElementsInArray method presented in this recipe allows for only two specified elements of an array (specified in the index1 and index2 arguments to this method).
The following code uses the SwapElementsInArray<T> method to swap the zeroth and fourth elements in an array of integers:
public static void TestSwapArrayElements()
{
int[] someArray = {1,2,3,4,5};
for (int counter = 0; counter < someArray.Length; counter++)
{
Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
someArray.SwapElementsInArray(0, 4);
for (int counter = 0; counter < someArray.Length; counter++)
{
Console.WriteLine("Element " + counter + " = " + someArray[counter]);
}
}This code produces the following output:
Element 0 = 1 ← The original array Element 1 = 2 Element 2 = 3 Element 3 = 4 Element 4 = 5 Element 0 = 5 ← The array with elements swapped Element 1 = 2 Element 2 = 3 Element 3 = 4 Element 4 = 1
Read now
Unlock full access