Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Object [,] to String[,]

I am trying to convert an object[,] array (with for example some integers in it) to a string[,] array. I wrote this piece of code but Visual Studio gives me an error saying:

Cannot implicitly convert String[] to String[,].

What argument should I give to the Array.ConvertAll function? Thanks a lot.

object[,] input = GetSelectedRange();

string[,] dst = Array.ConvertAll<object[,], string[,]>(
    input, 
    x => x.ToString()
);
like image 848
André van der Heijden Avatar asked Mar 14 '23 03:03

André van der Heijden


1 Answers

It would have been a lot easier if your item is object[][] rather than object[,]. But for object[,], why not using traditional method?

object[,] input = GetSelectedRange();
string[,] output = new string[input.GetLength(0), input.GetLength(1)];
for (int i = 0; i < input.GetLength(0); ++i)
    for (int j = 0; j < input.GetLength(1); ++j)
        output[i, j] = input[i, j]?.ToString(); //give additional ?. to check if your input is null

Suggestion by Olivier: to check if your input is null by using C#6 syntax ?.

Or, if you use lower version, use ternary operator:

object[,] input = GetSelectedRange();
string[,] output = new string[input.GetLength(0), input.GetLength(1)];
for (int i = 0; i < input.GetLength(0); ++i)
    for (int j = 0; j < input.GetLength(1); ++j)
        output[i, j] = input[i, j] == null ? null input[i, j].ToString();
like image 184
Ian Avatar answered Mar 19 '23 21:03

Ian