我正在构建一个ASP.net测验引擎,我正在使用我之前在Flash中做过的测验引擎作为ASP版本的模板。我坚持如何在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].@choice.toString();
// if the given answer is the correct answer then set that value to the arrcorrect
}
任何人都可以帮助我如何在ASP.net中获得上述动作脚本代码吗?
答案 0 :(得分:2)
要直接转换此代码,您将声明一个锯齿状数组,如下所示:
var answers = new string[questionCount][];
然后,您将使用LINQ to XML初始化外部数组的元素,如下所示:
foreach(var question in data.Elements("Question"))
answers[i] = question.Elements("Answer").Select(a => a.Value).ToArray();
您也可以在没有循环的情况下执行此操作,如下所示:
var answers = data.Elements("Question")
.Select(q => q)
.ToArray();
但是,最好将数组重构为QuizQuestion
类ReadOnlyCollection<String> AnswerChoices
。
例如:
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;}
}
修改LINQ to XML代码以适合您的XML格式。