I have seen how to cast an object to a string array using the code below,
string[] arr = ((IEnumerable)paraArray).Cast<object>()
.Select(x => x.ToString())
.ToArray();
My question though is if paraArray is a object (but the data is a multidimensional array) how can I cast it to a multidimensional string array?
You can't achieve this via ToArray. The best, IMHO, you can do is
object[,] paraArray = new object[,] {
{1, 2, 3 },
{4, 5, 6 },
};
...
string[,] arr = new string[paraArray.GetLength(0), paraArray.GetLength(1)];
for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
arr[i, j] = paraArray[i, j].ToString();
2d arrays are not very convenient when working with Linq, that's why often jagged arrays (array of array) are preferable:
object[][] paraArray = new object[][] {
new object[] {1, 2, 3 },
new object[] {4, 5, 6 },
};
...
// Working with jagged array is much easier than with 2d one
string[][] arr = paraArray
.Select(line => line
.Select(item => item.ToString())
.ToArray())
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With