views:

28

answers:

1

I'm building a ASP.net quiz engine and I'm using a previous quiz engine i did in Flash as a template for the ASP version. I'm stuck on how I can achieve the following code in ASP.net

// array to hold the answers
var arrAnswers:Array = new Array();
// create and array of answers for the given question
arrAnswers[i] = new Array();
// loop through the answers of each question
for (j=0; j<dataXML.question[i].answers.length(); j++) 
{
//array of answers for that given question is pulle from XML data
arrAnswers[i][j] = dataXML.question[i].answers[j][email protected]();
// if the given answer is the correct answer then set that value to the arrcorrect 
}

Can anyone help on how I can get above action script code in ASP.net?

+2  A: 

To convert this code directly, you would declare a jagged array, like this:

 var answers = new string[questionCount][];

You would then initialize the elements of the outer array using LINQ to XML, like this:

foreach(var question in data.Elements("Question"))
    answers[i] = question.Elements("Answer").Select(a => a.Value).ToArray();

You could also do it without a loop, like this:

var answers = data.Elements("Question")
    .Select(q => q)
    .ToArray();

However, it would be best to refactor the array into a QuizQuestion class with a ReadOnlyCollection<String> AnswerChoices.

For example:

class QuizQuestion {
    public QuizQuestion(XElement elem) {
        Text = elem.Element("Text").Value;
        AnswerChoices = new ReadOnlyCollection<String>(
            elem.Elements("Answer").Select(a => a.Value).ToArray()
        );
        CorrectAnswerIndex = elem.Attr("CorrectAnswer");
    }
    public string Text { get; private set; }
    public ReadOnlyCollection<String> AnswerChoices { get; private set; }
    public int CorrectAnswerIndex { get; private set;} 
}

Modify the LINQ to XML code to fit your XML format.

SLaks
when i try to declare the jagged array, i get an error The contextual keyword 'var' may only appear within a local variable declarationi know what the error message is trying to say, but i need to declare this variable as a global variable, not a local one.
c11ada
Replace `var` with `string[][]`.
SLaks