### Manipulating doublearrays – an extension method

Thursday, March 22nd, 2012This is how you use it:

byte[,] data = new byte[3,3]; byte[,] manipulatedData =data.GetManipulatedCopy(ArrayManipulation.RotateClockwise);

Here is the complete class:

using System; // Class with extensionmethods to manipulate doublearrays with // Jakob Krarup (www.xnafan.net) // Use, alter and redistribute this code freely, // but please leave this comment namespace ArrayManipulation { /// <summary> /// Defines how to manipulate an array /// </summary> public enum ArrayManipulation { /// <summary> /// Moves all values around the array clockwise /// </summary> RotateClockwise, /// <summary> /// Moves all values around the array counterclockwise /// </summary> RotateCounterClockwise, /// <summary> /// Swaps all values from the top to bottom and vice-versa /// </summary> FlipTopToBottom, /// <summary> /// Swaps all values from left to right and vice-versa /// </summary> FlipRightToLeft } public static class ArrayExtensions { /// <summary> /// Implements easy doublearray manipulations /// </summary> /// <typeparam name="T">The type of the values in the array</typeparam> /// <param name="matrix">The doublearray</param> /// <param name="manipulation">How to manipulate the array</param> /// <returns>A copy of the array with the values as ordered</returns> public static T[,] GetManipulatedCopy<T>(this T[,] matrix, ArrayManipulation manipulation) { int width = matrix.GetLength(0); int height = matrix.GetLength(1); T[,] ret = null; switch (manipulation) { //if we are rotating the matrix, //we need to swap width and height sizes case ArrayManipulation.RotateClockwise: case ArrayManipulation.RotateCounterClockwise: ret = new T[height, width]; break; //otherwise we create an array with the same size case ArrayManipulation.FlipTopToBottom: case ArrayManipulation.FlipRightToLeft: ret = new T[width, height]; break; default: throw new ArgumentOutOfRangeException("Invalid manipulation : " + manipulation); } //for all values in the source matrix... for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { //copy the values to the new array //choosing position depending on the wanted manipulation switch (manipulation) { case ArrayManipulation.RotateCounterClockwise: ret[y, width - x - 1] = matrix[x, y]; break; case ArrayManipulation.RotateClockwise: ret[height - y - 1, x] = matrix[x, y]; break; case ArrayManipulation.FlipTopToBottom: ret[x, height - 1 - y] = matrix[x, y]; break; case ArrayManipulation.FlipRightToLeft: ret[width - 1 - x, y] = matrix[x, y]; break; } } } //return the new array return ret; } } }

Searchwords for Google: extensionmethod, rotate double arrays, manipulate two-dimensional, twodimensional arrays, non-jagged