Alex Rivera | Logout

What's the best way to extract a one-dimensional array from a rectangular array in C#?

Asked 2008-10-24T05:21:00.247
14

Say I have a rectangular string array - not a jagged array

string[,] strings = new string[8, 3];

What's the best way to extract a one-dimensional array from this (either a single row or a single column)? I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in.

Bonus points for converting the extracted string array to an object array.

Edit
Report

1 Answer

8

For a rectangular array:

string[,] rectArray = new string[3,3] { 
    {"a", "b", "c"}, 
    {"d", "e", "f"}, 
    {"g", "h", "i"} };

var rectResult = rectArray.Cast<object>().ToArray();

And for a jagged array:

string[][] jaggedArray =  { 
    new string[] {"a", "b", "c", "d"}, 
    new string[] {"e", "f"}, 
    new string[] {"g", "h", "i"} };

var jaggedResult = jaggedArray.SelectMany(s => s).Cast<object>().ToArray();
answered 2008-10-24T13:15:41.557

Your Answer