Mark
Mark

Reputation: 419

Invert array of arrays

I have a string[][].
Each entry in the list represents a column in a document, each member of the array represents a line in this column.
Example:

0.0 | 1.0 | 2.0  
0.1 | 1.1 | 2.1  
0.2 | 1.2 | 2.2  

Now I to write this to a file. However if I do that I first need to convert them to string[] where each element is one line, joined by let's say commas (.csv file).

Any suggestions how to do that?

I tried wrapping my head around it with several loops taking the n-th element of each column and stuff it in a buffer and then join these buffers together. I am sure I will get it to work that way, however I don't think that it is in any way efficient or good style.

Upvotes: 1

Views: 289

Answers (2)

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20640

If you're starting with this:

string[][] original = new[] {
    new[] { "0.0", "0.1", "0.2" },
    new[] { "1.0", "1.1", "1.2" },
    new[] { "2.0", "2.1", "2.2" }
};

Then you can do this to work with each row in turn:

for (int column = 0; column < original.Length; column++)
{
    string row = string.Join(",", original.Select(o => o[column]));
    Console.WriteLine(row);    
}

This yields the following output:

0.0,1.0,2.0
0.1,1.1,2.1
0.2,1.2,2.2

Upvotes: 1

kevin
kevin

Reputation: 2213

Ok simple: assume that the entire array is rectangular (i.e. same number of items in all rows and same number of items in all columns). What you have to do now, is given an item at (x,y), change its position to (y,x).

So:

var array2 = new string[array1.GetLength(0), array1.GetLength(1)];
for(int i=0;i<array2.GetLength(0);i++){
    for(int j=0;j<array2.GetLength(1);j++)
        array2[i,j] = array1[j][i]; //this is the magic line
}

Upvotes: 3

Related Questions