有没有办法使用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可能会起作用,但到目前为止答案已经没有了。
答案 0 :(得分:1)
不,我认为你不能一步完成转换,但我可能错了。但是你当然可以创建一个新数组并从旧数组复制到新数组:
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
的二维重载,并不比上面的代码复杂得多:
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;
}
答案 1 :(得分:1)
您可以为二维数组编写自己的ConvertAll
:
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;
}
答案 2 :(得分:0)
string[][] strings = ((object[][])range.Value)
.Select(x => x.Select(y => y.ToString()).ToArray()).ToArray();
编辑:关于object [,]而不是object [] []的说明显然使这种方法过时了。一个有趣的问题;多维数组非常有限。