ASP.Net c# adding items to jagged array

2019-09-17 11:48发布

im trying to add items to jagged array's, the data is being pulled from a datarowview, i have the following code

foreach (DataRowView answer in AnswersInQuestion)
{
    answersJArray[index] = new string[noOfAnswersInQuestion];
    answersJArray[index][j] = answer["ChoiceText"].ToString();
    j++;
}

the first item gets added in fine, but when the 2nd item is put in the first item is set to null again. so for example the first time round this is what the array will look like

arr[0][0] = answer 1
arr[0][1] = null
arr[0][2] = null
arr[0][3] = null

and the 2nd time round the array will look like

arr[0][0] = null
arr[0][1] = answer 2
arr[0][2] = null
arr[0][3] = null

can any one help me on this !!

thanks

4条回答
Luminary・发光体
2楼-- · 2019-09-17 11:58

Your constructor is being called each time (hence the first item being set to null). Put your string array constructor outside of your for-each loop (perhaps in its own loop.

查看更多
一夜七次
3楼-- · 2019-09-17 12:04

My approach is to create a hashset of string arrays then populate at will, and at the end, convert ToArray()

e.g.

HashSet<string[]> data = new HashSet<string[]>();

data.Add(new string[] { "mode", "create" });
data.Add(new string[] { "title", this.TextBoxCreateTitle.Text });

data.ToArray();      // our jagged array
查看更多
放荡不羁爱自由
4楼-- · 2019-09-17 12:08

What is index? You don't seem to be incrementing it, and each time through your foreach you're creating a new one and dumping it into the same index. Basically rewriting it each time.

You might find more use in using a List to accomplish this jagged array. It will make adding/removing a little easier, and it might help a touch in enumerating.

查看更多
乱世女痞
5楼-- · 2019-09-17 12:09

You need a nested loop, because you are creating a brand new array each time and blowing the old one away.

//souround with a loop that increments index whenever you want to create a new group of questions
    answersJArray[index] = new string[noOfAnswersInQuestion];
    foreach (DataRowView answer in AnswersInQuestion)
    {

        answersJArray[index][j] = answer["ChoiceText"].ToString();
        j++;
    }
查看更多
登录 后发表回答