I have 3 classes
public class Test
{
private List<Question> _questions;
private string _text;
public string Text
{
get
{
return _text;
}
}
//...
}
public class Question
{
private List<Answer> _answers;
private string _text;
开发者_C百科
public string Text
{
get
{
return _text;
}
}
//...
}
public class Answer
{
private string _text;
private bool _isCorrect;
public string Text
{
get
{
return _text;
}
}
public bool isCorrect
{
get
{
return _isCorrect;
}
}
//...
}
I need to select a Text from Questions and Text from Answers, where Answer is correct.
I can only select correct Answers.Test t;
//Initializing t
var r = t.SelectMany<Question, Answer>(q => q).Where<Answer>(a => a.isCorrect == true);
My question is: How to select a Text from Questions and Text from Answers, where Answer is correct. I need to make a linq to objects query.
Assuming Test
implements IEnumerable<Question>
and Question
implements IEnumerable<Answers>
:
var questionsWithCorrectAnswers = myTest
.SelectMany(q => q.Where(a => a.IsCorrect)
.Select(a => new { Question = q, Answer = a }));
First off, your Questions and Answers are private. I'll assume you have a public accessor Questions and Answers, respectively.
Try this:
var results = from q in t.Questions
where q.Answers.Any(a=>a.isCorrect)
select new {Question = q, CorrectAnswers = q.Answers.Where(a=>a.isCorrect)};
You can now reference results.Question and results.CorrectAnswers. You can also select a new Question where the Answers list contains only correct Answers.
精彩评论