ASP.Net c# adding items to jagged array

依然范特西╮ 提交于 2020-01-07 06:40:33

问题


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


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/2320453/asp-net-c-sharp-adding-items-to-jagged-array

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