How to return a jagged array

筅森魡賤 提交于 2020-01-07 02:02:17

问题


I have a function which use a 2D jagged array to save records from an SQL query.

How do return the jagged array correctly?

I tried something like:

public string[][] GetResult()
{
    return result;
}

And in my main programm:

string[][] test = new string[server1.GetResult().Length][];
test = server1.GetResult();

Well, as expected, it didn't work.

I don't know how to fix my problem.


回答1:


Jagged arrays are simply arrays of arrays.

In your code:

string[][] test = new string[server1.GetResult().Length][];
test = Gronforum.GetResult();

You first assign a new array to test, then overwrite it with the return value from GetResult(). The code does the same as:

string[][] test = Gronforum.GetResult();

Now the GetResult() should return a string[][] - try this to get a feel of working with jagged arrays:

public string[][] GetResult()
{
    string[][] result = new string[2][];
    result[0] = new string[] { "1", "2" };
    result[1] = new string[2];
    result[1][0] = "a";
    result[1][1] = "b";
    return result;
}

You could supply a reference to the result of the SQL operation to that method so it has access to the data, to "convert" it to a string[][].



来源:https://stackoverflow.com/questions/7430523/how-to-return-a-jagged-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!