【问题标题】:Initialize and return jagged array in one line在一行中初始化并返回锯齿状数组
【发布时间】:2014-02-04 21:38:55
【问题描述】:

目前我正在这样做

public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        var result = new int[0][];
        result[0] = new int[0];
        return result;
    }
    // Other code,
}

现在我只想返回 [0][0] 的空锯齿数组。是否可以将三行减少为一。我想实现这样的目标

public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        return new int[0][0];
    }
    // Other code,
}

有可能吗?

【问题讨论】:

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


    【解决方案1】:

    在一般情况下,您可以让编译器为您计算元素:

        public int[][] JaggedInts()
        {
            return new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
        }
    

    或者如果你想要它非常紧凑,使用表达式主体:

     public int[][] JaggedInts() => new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
    

    既然你要求一个空的锯齿状数组,你已经有了它:

    var result = new int[0][];
    

    您问题的下一行将引发运行时异常,因为 [0] 是数组中的第一个元素,其长度必须是 1 个或多个元素;

     result[0] = new int[0];  // thows IndexOutOfRangeException: Index was outside the bounds of the array.
    

    这就是我认为您在一行中要求的内容:

    public int[][] Empty() => new int[0][];
    

    【讨论】:

      【解决方案2】:

      通过返回锯齿状数组的值,它会给你一些模棱两可的结果,如果你想返回锯齿状数组的某个特定索引的某个特定值,你可以通过将它们分配给变量来返回

       public static int  aaa()
          {
      
              int[][] a = new int[2][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
              int abbb=a[0][0];
              Console.WriteLine(a[0][0]);
              return abbb;
          }
      

      以下代码将返回 1,因为这是锯齿数组的第一个元素

      【讨论】:

        【解决方案3】:

        请在此处查看https://stackoverflow.com/a/1739058/586754 及以下内容。

        你需要创建一些辅助函数,然后它就变成了单行。

        (也在寻找单行解决方案。)

        【讨论】:

          猜你喜欢
          • 2010-12-16
          • 1970-01-01
          • 2019-06-17
          • 1970-01-01
          • 1970-01-01
          • 2011-08-21
          • 2010-11-09
          • 1970-01-01
          • 2014-05-03
          相关资源
          最近更新 更多