开发者

How can I convert a boxed two-dimensional array to a two-dimensional string array in one step?

Is there a way to convert a boxed two-dimensional array to a two-dimensional string array in one step using C#/.NET Framework 4.0?

using ( MSExcel.Application app = MSExcel.Application.CreateApplication() ) {
    MSExcel.Workbook book1 = app.Workbooks.Open( this.txtOpen_FilePath.Text );
    MSExcel.Worksheet sheet1 = (MSExcel.Worksheet)book1.Worksheets[1];
    MSExcel.Range range = sheet1.GetRange( "A1", "F13" );
    object value = range.Value; //the value is boxed two-dimensional array
}

I'm hopeful that some form of Array.Co开发者_开发问答nvertAll might be made to work but so far the answer has eluded me.


No, I do not think you can make the conversion in one step, but I might be wrong. But you can of course create a new array and copy from the old one to the new one:

object value = range.Value; //the value is boxed two-dimensional array
var excelArray = value as object[,];
var height = excelArray.GetLength(0);
var width = excelArray.GetLength(1);
var array = new string[width, height];
for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
        array[i, j] = excelArray[i, j] as string;
}

Edit:

Here is a two-dimensional overload of Array.ConvertAll which is not that much more complicated than the code above:

public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
{
    if (array == null)
    {
        throw new ArgumentNullException("array");
    }
    if (converter == null)
    {
        throw new ArgumentNullException("converter");
    }
    int height = array.GetLength(0);
    int width = array.GetLength(1);
    TOutput[,] localArray = new TOutput[width, height];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
            localArray[i, j] = converter(array[i, j]);
    }
    return localArray;
}


You can write your own ConvertAll for two-dimensional arrays:

public static TOutput[,] ConvertAll<TInput, TOutput>(
    this TInput[,] array, Func<TInput, TOutput> converter)
{
    int length0 = array.GetLength(0);
    int length1 = array.GetLength(1);

    var result = new TOutput[length0, length1];

    for (int i = 0; i < length0; i++)
        for (int j = 0; j < length1; j++)
            result[i, j] = converter(array[i, j]);

    return result;
}


string[][] strings = ((object[][])range.Value)
    .Select(x => x.Select(y => y.ToString()).ToArray()).ToArray();

Edit: The clarification about object[,] instead of object[][] obviously makes this approach obsolete. An interesting problem; multidimensional arrays are quite limited.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜