Federico
Federico

Reputation: 799

Serialization and deserialization of an int matrix c#

I'm using a c# WCF service and I need to return a int[,] to the client in one of my method. The problem is multidimensional arrays are not supported by WCF so I think my only option is returning a byte array in this way:

    public byte[] DistanceMatrix()
    {
        int[,] matrix;

        //DOING THINGS HERE

        IFormatter formatter = new BinaryFormatter();
        var ms = new MemoryStream();
        formatter.Serialize(ms, matrix);

        return ms.ToArray();
    }

But I don't know how to deserialize the byte[] back to an int[,].

Upvotes: 4

Views: 2008

Answers (1)

chridam
chridam

Reputation: 103375

This excellent blog post by Josh Reuben can help you:

Extension methods that will allow you to convert prior to serialization and convert back after deserialization:

    public static T[,] ToMultiD<T>(this T[][] jArray)
    {
        int i = jArray.Count();
        int j = jArray.Select(x => x.Count()).Aggregate(0, (current, c) => (current > c) ? current : c);


        var mArray = new T[i, j];

        for (int ii = 0; ii < i; ii++)
        {
            for (int jj = 0; jj < j; jj++)
            {
                mArray[ii, jj] = jArray[ii][jj];
            }
        }

        return mArray;
    }

    public static T[][] ToJagged<T>(this T[,] mArray)
    {
        var cols = mArray.GetLength(0);
        var rows = mArray.GetLength(1);
        var jArray = new T[cols][];
        for (int i = 0; i < cols; i++)
        {
            jArray[i] = new T[rows];
            for (int j = 0; j < rows; j++)
            {
                jArray[i][j] = mArray[i, j];
            }
        }
        return jArray;
    }

Upvotes: 3

Related Questions