我已经看到了如何使用下面的代码将对象转换为字符串数组,

string[] arr = ((IEnumerable)paraArray).Cast<object>()
                             .Select(x => x.ToString())
                             .ToArray();


我的问题是,如果paraArray是对象(但数据是多维数组),我如何将其转换为多维字符串数组?

最佳答案

您无法通过ToArray实现。最好的,恕我直言,你可以做的是

  object[,] paraArray = new object[,] {
    {1, 2, 3 },
    {4, 5, 6 },
  };

  ...

  string[,] arr = new string[paraArray.GetLength(0), paraArray.GetLength(1)];

  for (int i = 0; i < arr.GetLength(0); ++i)
    for (int j = 0; j < arr.GetLength(1); ++j)
      arr[i, j] = paraArray[i, j].ToString();


2d数组在使用Linq时不是很方便,这就是为什么经常使用锯齿形数组(array of array)的原因:

  object[][] paraArray = new object[][] {
    new object[] {1, 2, 3 },
    new object[] {4, 5, 6 },
  };

  ...

  // Working with jagged array is much easier than with 2d one
  string[][] arr = paraArray
    .Select(line => line
       .Select(item => item.ToString())
       .ToArray())
    .ToArray();

10-08 14:03