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

亡梦爱人 提交于 2019-12-18 09:26:54

问题


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.ConvertAll might be made to work but so far the answer has eluded me.


回答1:


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;
}



回答2:


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;
}



回答3:


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.



来源:https://stackoverflow.com/questions/6065695/how-can-i-convert-a-boxed-two-dimensional-array-to-a-two-dimensional-string-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!