views:

44

answers:

2

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;

   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.

+1  A: 

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 }));
Timwi
I havent got an access for Questions in Test. I can only get an enumerator.
Sergey Gavruk
@Sergey: Fixed.
Timwi
+1  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.

KeithS