简体   繁体   中英

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]. 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;

 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#

Please have a look here https://stackoverflow.com/a/1739058/586754 and below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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