首先,您必須決定如何將問題和響應表示爲數據結構。我建議代表有足夠的類的問題和答案(我使用VS 2017年/ C#7.0的語法):
public class Choice
{
public Choice (string choiceText, string answer)
{
ChoiceText = choiceText;
Answer = answer;
}
public string ChoiceText { get; }
public string Answer { get; }
}
public class Question
{
public Question (string questionText)
{
QuestionText = questionText;
}
public string QuestionText { get; }
public List<Choice> Choices { get; } = new List<Choice>();
}
現在你可以開始閱讀文件和提出的問題和答案到結構
var questions = new List<Question>();
var Question lastQuestion = null;
foreach (string line in File.ReadLines(path)) {
if (line.StartsWith("*")) {
// We have a new question. Create a question object and add it to the list.
lastQuestion = new Question(line.Substring(1));
questions.Add(lastQuestion);
} else if (lastQuestion != null) {
// We have a term related to the last question. Add it to the last question.
// Split the line at the equal sign.
string[] parts = line.Split("=", StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0) {
// We have at least one part that is not empty. Let’s assume it’s the part before
// the "=". If we have a second part, insert it as well, otherwise insert null.
var choice = new Choice(parts[0], parts.Length > 1 ? parts[1] : null);
lastQuestion.Add(choice);
}
}
}
但是,我注意到您的示例文件包含2個不同類型的問題。有些人在等號後有答案,而另一些人則將選擇和答覆分開。所以,你必須擴展解決方案來考慮這一點。
你的問題非常不明確,所以很難給你一個合適的答案。下一次,提前想一想,並提出更具體和更精確的問題。另外,在Stack Overflow上,我們更傾向於提供迄今爲止嘗試過的代碼示例。
我不確定我是否正確理解你想要什麼,但也許你可以將所有以*開頭的行存儲在列表結構中,然後生成一個隨機數來訪問該列表中的項目。 –
如何做到這一點? – Pavle
你到目前爲止嘗試過什麼?你是否有一些數據結構,你想要存儲的問題? –