首先,您必须决定如何将问题和响应表示为数据结构。我建议代表有足够的类的问题和答案(我使用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
你到目前为止尝试过什么?你是否有一些数据结构,你想要存储的问题? –