我在数据库中有问答表。我使用 Join 来选择带有答案的问题,并尝试使用 LINQ 获取问题和答案。这是我的代码:
List<Question> newQuestionList =
(from q in dt.AsEnumerable()
where (q.Field<Guid>("Question") != null))
select new Question
{
Oid = q.Field<Guid>("Question"),
QuestionContext = q.Field<String>("QuestionContext"),
Priority = q.Field<Int32>("Priority"),
Order = q.Field<Int32>("OrderQuestion"),
Subject = q.Field<Guid>("Subject"),
Answers = (from a in dt.AsEnumerable()
where a.Field<Guid>("Question") == q.Field<Guid>("Question")
select
new Answer
{
Oid = a.Field<Guid>("AnswerOid"),
AnswerContext = a.Field<String>("Answer"),
IsCorrect = a.Field<bool>("Correct")
}).ToList()
}).Distinct().ToList();
有很多行具有相同的问题(Id)。它遍历所有。对于一个问题,我只需要迭代一次。如果我有 7 个问题,并且每个问题都有 4 个答案,那么这段代码会给我一个计数为 28 的列表。它的计数必须是 7。有人可以帮忙吗?
public class Question
{
private Guid oid;
public Guid Oid
{
get { return oid; }
set { oid = value; }
}
private string questionContext;
public string QuestionContext
{
get { return questionContext; }
set { questionContext = value; }
}
private int priority;
public int Priority
{
get { return priority; }
set { priority = value; }
}
private Guid subject;
public Guid Subject
{
get { return subject; }
set { subject = value; }
}
private List<Answer> answers;
public List<Answer> Answers
{
get { return answers; }
set { answers = value; }
}
private int order;
public int Order
{
get { return order; }
set { order = value; }
}
}
public class Answer
{
private Guid oid;
public Guid Oid
{
get { return oid; }
set { oid = value; }
}
private string answerContext;
public string AnswerContext
{
get { return answerContext; }
set { answerContext = value; }
}
private bool isCorrect;
public bool IsCorrect
{
get { return isCorrect; }
set { isCorrect = value; }
}
}