如何在C#中访问和重新格式化Jagged数组

时间:2014-12-17 18:17:38

标签: c# arrays multidimensional-array jagged-arrays

我在c#中有二维数组,如下所示:

int[][] 2darray = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

如何将一列作为普通数组,如

int[] array = 2darray[1][]; //example, not working

并且

int[] array = {3,4};

? 感谢。

4 个答案:

答案 0 :(得分:4)

您的代码无法编译的原因有多种

这种方式有效:

int[][] array2d = { new[]{ 1, 2 }, new[]{ 3, 4 }, new[]{ 5, 6 }, new[]{ 7, 8 } };

int[] array = array2d[0];

问题:

  • 2darray不是有效的变量名称
  • 索引错误
  • 原始数组的初始化错误


编辑: 正如@heltonbiker所述,如果您需要第一列的所有元素,您可以使用:

int[] col = array2d.Select(row => row[0]).ToArray();

答案 1 :(得分:3)

对于包含两列和四行的数组,可以这样使用LINQ:

using System.Linq;

first_column = _2darray.Select(row => row[0]).ToArray();

请注意,更改第一个或第二个数组不会更改另一个数组。

答案 2 :(得分:2)

您在C#中混淆了jagged arraysmultidimensional arrays。虽然它们相似,但略有不同。锯齿状数组中的行可以具有不同数量的元素,而在2D数组中,它们具有相同的长度。因此,在处理锯齿状数组时,您需要记住为缺少的列元素编写处理。我在下面编写了一个示例控制台应用程序,以显示它们如何工作 - 它使用0作为缺少元素的替代,但是您可以抛出错误等。:

using System.Collections.Generic;

namespace JaggedArrayExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //jagged array declaration
            int[][] array1;

            //jagged array declaration and assignment
            var array2 = new int[][] {
                          new int[] { 1, 2 },
                          new int[] { 3, 4 },
                          new int[] { 5, 6 },
                          new int[] { 7, 8 }
                        };

            //2D-array declaration
            int[,] array3;

            //2D-array declaration and assignment (implicit bounds)
            var array4 = new int[,] {{1, 2}, {3, 4}, {5, 6}, {7, 8}};

            //2D-array declaration and assignment (explicit bounds)
            var array5 = new int[4, 2] {{1, 2}, {3, 4}, {5, 6}, {7, 8}};

            //get rows and columns at index
            var r = GetRow(array2, 1); //second row {3,4}
            var c = GetColumn(array2, 1); //second column {2,4,6,8}
        }

        private static int[] GetRow(int[][] array, int index)
        {
            return array[index]; //retrieving the row is simple
        }

        private static int[] GetColumn(int[][] array, int index)
        {
            //but things get more interesting with columns
            //especially if jagged arrays are involved
            var retValue = new List<int>();
            foreach (int[] r in array)
            {
                int ub = r.GetUpperBound(0);
                if (ub >= index) //index within bounds
                {
                    retValue.Add(r[index]);
                }
                else //index outside of bounds
                {
                    retValue.Add(0); //default value?
                    //or you can throw an error
                }
            }
            return retValue.ToArray();
        }
    }
}

答案 3 :(得分:0)

试试这个,它应该有用

int[] array = array2d[1];

将变量的名称更改为array2d,您不能拥有以数字开头的变量,变量可以以字母或下划线开头。