myermian
myermian

Reputation: 32515

DataContract + Multi-dimensional Arrays -- Any solution for this?

From MSDN:

Combining collection types (having collections of collections) is allowed. Jagged arrays are treated as collections of collections. Multidimensional arrays are not supported.

So, if you can't normally serialize a multidimensional array, how does one get around this efficiently? My thought is to have a property that flattens the array and serialize that collection and unflatten it during deserialization, but I'm not sure if that's efficient?

Anyone find a solution this before?


I should note that the reason I think flattening might work is because my dimensions are a fixed value (they are hard-coded).

Upvotes: 4

Views: 4235

Answers (3)

Andreas
Andreas

Reputation: 6465

Maybe with an extension method:

public static string[][] Jaggedize(this string[,] input) {
  string[][] output = new string[input.GetLength(0)][];
  for (int i = 0; i < input.GetLength(0); i++) {
    output[i] = new string[input.GetLength(1)];
    for (int j = 0; j < input.GetLength(1); j++) {
      output[i][j] = input[i, j];
    }
  }
  return output;
}

Upvotes: 3

jklemmack
jklemmack

Reputation: 3636

Any time you rip through a 2-D array you're expending O(n) effort (or one "processing" unit per item in the input). It's not much trouble to convert between 2-D and 1-D and back as you said. Unless you're dealing in really high volumes (array size of call frequency of the web service), or on a highly constrained system (.Net Compact or .Net Micro Frameworks), I doubt this would really be a big issue. Things like sorting are what get expensive.

       string[,] input = new string[5, 3];
       string[] output = new string[15];

       for (int i = 0; i < input.GetUpperBound(0); i++)
       {
           for (int j = 0; j < input.GetUpperBound(1); j++)
           {
               output[j * input.GetUpperBound(j) + i] = input[i, j];
           }
       }

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273244

Yes, you could flatten it or Jagged-ize it, whatever is more convenient.

Upvotes: 3

Related Questions