Click here to Skip to main content
15,947,504 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hello Codeproject,

How would I converted

C#
[XmlIgnore]
public Block[,] _Blocks { get; set; }


To:

C#
public Block[] _Blocks { get; set; }


And back to:

C#
public Block[] _Blocks { get; set; }
,

I need this for my XML Serializer, because I need to save the list of blocks, but the XML serializer does not allow Multi-dimensional array.
Posted
Updated 26-Dec-12 1:53am
v2
Comments
[no name] 26-Dec-12 8:28am    
Why do u need a XML serializer property? You can customize your own property.
Yvar Birx 26-Dec-12 8:40am    
What do you mean ?
Yvar Birx 26-Dec-12 8:50am    
I got this as a propery because that is how XML Serializer works, and I need to save this in a file and load it out later.
[no name] 26-Dec-12 8:52am    
Can you specify your requirement more briefly?
Yvar Birx 26-Dec-12 8:56am    
I am not really sure how to explain it more briefly. I got an multi-dimensional array of a 'block' class, I need to be able to convert that into a single array so I can use the XML serializer to save it in a file. I just don't know how to convert a multi into a single array and back.

1 solution

Here's some sample code of an int[] conversion if you don't have any specifications. NOTE: this only works with multi-dimensional array's with the same width and height...

C#
static int[,] SingleToMulti(int[] array)
{
     int index = 0;
     int sqrt = (int)Math.Sqrt(array.Length);
     int[,] multi = new int[sqrt, sqrt];
     for (int y = 0; y < sqrt; y++)
     {
        for (int x = 0; x < sqrt; x++)
        {
            multi[x, y] = array[index];
            index++;
        }
      }
      return multi;
}


C#
static int[] MultiToSingle(int[,] array)
{
     int index = 0;
     int width = array.GetLength(0);
     int height = array.GetLength(1);
     int[] single = new int[width * height];
     for (int y = 0; y < height; y++)
     {
         for (int x = 0; x < width; x++)
         {
            single[index] = array[x, y];
            index++;
         }
     }
     return single;
}
 
Share this answer
 
Comments
Yvar Birx 27-Dec-12 8:54am    
Cheers mate ! Thanks finally works !
One question, how did you know to square the number ?
austinbox 27-Dec-12 14:04pm    
You don't, if you wanted to use different sized lengths just pass them in as parameteres.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900