我怎么能转换成一个盒装的二维数组二维字符串数组一步到位? [英] How can I convert a boxed two-dimensional array to a two-dimensional string array in one step?
问题描述
有没有办法用一个盒装二维数组转换为二维字符串数组在一个步骤C#/。NET Framework 4.0中?
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
}
我希望某种形式的Array.ConvertAll可能进行的工作,但到目前为止,答案已经躲避我。
I'm hopeful that some form of Array.ConvertAll 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;
}
编辑:
下面是 Array.ConvertAll
的二维超载这是不是远远超过了code以上复杂的:
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;
}
这篇关于我怎么能转换成一个盒装的二维数组二维字符串数组一步到位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!