简体   繁体   English

初始化并返回锯齿状数组

[英]Initialize and return jagged array in one line

Currently I am doing this 目前我正在这样做

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

Now in this I only want to return empty jagged array of [0][0]. 现在,我只想返回[0] [0]的空锯齿数组。 Is it possible to reduce three lines to one. 是否可以将三行减少为一行。 I want to achieve something like this 我想实现这样的目标

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

Is it possible? 可能吗?

In the general case, you can let the compiler count elements for you: 通常,您可以让编译器为您计算元素:

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

Or if you want it very compact, use an expression body: 或者,如果您希望它非常紧凑,请使用表达式主体:

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

Since you asked for an empty jagged array, you already had it: 由于您要求一个空的锯齿状数组,因此您已经有了它:

var result = new int[0][];

The next line in your question will throw a run-time exception, since [0] is the first element in an array, which must be 1 or or more elements in length; 问题的下一行将引发运行时异常,因为[0]是数组中的第一个元素,长度必须为1个或多个元素;

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

Here is what I think you asked for in just one line: 这是我想您只要求一行的内容:

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

try out this sample page. 试试这个示例页面。 Hope that help 希望对您有所帮助

Jagged Array in C# C#中的锯齿状数组

Please have a look here https://stackoverflow.com/a/1739058/586754 and below. 请在这里https://stackoverflow.com/a/1739058/586754及以下查看。

You will need to create some helper functions and then it becomes a one-liner. 您将需要创建一些帮助程序功能,然后它成为一个单一的行。

(Also was looking for a 1-line-solution.) (也正在寻找一线解决方案。)

by returning value of jagged array its give you some ambiguous result,if you want to return some specific value of some specific index of jagged array you can return by assigning them to variable 通过返回锯齿形数组的值,可以得到一些模棱两可的结果,如果您想返回锯齿形数组的某些特定索引的特定值,则可以通过将其分配给变量来返回

 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;
    }

the following code will return 1 becoz this is first element of jagged array 下面的代码将返回1,因为这是锯齿状数组的第一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM