开发者

Counting items in specific dimension of multidimensional array (C#)

I am using a multidimensional array to keep track of answers:

public string[,] answersArray = new string[50, 10];
开发者_StackOverflow社区

The first dimension of the array keeps track of questions (max. 50 questions), whereas the second dimension keeps track of each question's answers (max. 10). The amount of answers for each question is variable. Upon loading a question, I want to determine the amount of answers for that particular question. Then I can use that amount in a for loop to load and show these answers. Is there an easy way to obtain this, or would I have to write something myself? I know I could just declare another array to keep track of the amount of answers for each question, and just use that to get it done, but I was just wondering if there was an easier solution.


It sounds like you don't want a rectangular array as you've currently got, but instead an array of arrays, e.g.

string[][] answers = new string[50][];

Then you can populate each array with an array of the right size.

However, another alternative would be to avoid using arrays entirely - use List<T> which will grow as you need it to. In particular, you might want to have a List<Question> where a Question contains the question text itself and a List<Answer> (or possibly just a List<string>) for the answers.

The fact that arrays need to be sized up-front is one reason they should be considered "somewhat harmful".

If you really want to stick with your original approach, then obviously you know you've got 10 elements in each "row" of the array - you'd have to loop to find the first null value (if any) to indicate how many answers have actually been populated.


var dim1 = answersArray.GetLength(0); // 50
var dim2 = answersArray.GetLength(1); // 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜