Archive for the ‘Extension Methods’ Category

Manipulating doublearrays – an extension method

Thursday, March 22nd, 2012
arraymanipulations

I’ve been fiddling around with returning JSON from an Asp.net MVC solution and getting it in Jquery using the $.getJSON method. Unfortunately – when the default JSON serializer in .net serializes my doublearrays it takes the values of the first column first, then the next column, etc. I would like it to serialize it as one row, then the next, etc.

I am aware that this is default behavior and that I could just populate the doublearray with rows as columns and vice versa, but I find it more intuitive to be able to refer to the first indexer in an array as x and the second as y, like this:

byte[,] data = new byte[3,3];
int x = 2;
int y = 1;
data[x,y] = 1;

Therefore I created a little extension method for manipulating doublearrays. You may find it helpful if you need to rotate an array, or swap values vertically or horizontally.

You can perform multiple operations by chaining the manipulations.

This is how you use it:

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

Download Vs2010 project

Download Class file

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

XNA extension methods page

Sunday, January 24th, 2010

Just a short note to let you know that I will gather my extensionmethods on a separate page with sample usage for handy reference.

MouseState ExtensionMethod

Wednesday, January 20th, 2010

Just a little helpermethod to get the mouse's position as a Vector2.

For those of you who still haven't gotten started with extension methods here's a quick writeup'n'sample

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace XNAFAN
{
public static class MouseStateExtensionMethods
{

///

/// Returns the mouseposition as a Vector2
///

/// The current MouseState /// The mouseposition as a Vector2
public static Vector2 GetPosition(this MouseState mouse)
{
return new Vector2(mouse.X, mouse.Y);
}
}
}

This way you don't have to convert x and y every time along the lines of
MouseState mouseState = Mouse.GetState();
Vector2 position = new Vector2(mouseState.X, mouseState.Y);

Instead you just add a reference to the code with the extensionmethod and this enables you to write:

Vector2 position = mouseState.GetPosition();

Nifty - eh...? :-)