views:

694

answers:

4

I have a Question class that has public List property that can contain several Answers.

I have a question repository which is responsible for reading the questions and its answers from an xml file.

So I have a collection of Questions (List) with each Question object having a collection of Answers and I'd like to query this collection of Questions for an Answer (ie by its Name) by using Linq. I don't know how to do this properly.

I could do it with a foreach but I'd like to know whether there is a pure Linq way since I'm learning it.

+6  A: 
from question in Questions
from answer in question.Answers
where answer.Name == something
select question // or select answer
ybo
+7  A: 

To find a answer.

questions.SelectMany(q => q.Answers).Where(a => a.Name == "SomeName")

To find the question of a answer.

question.Where(q => q.Answers.Any(a => a.Name == "SomeName"))

In fact you will get collections of answers or questions and you will have to use First(), FirstOrDefault(), Single(), or SingleOrDefault() depending on your needs to get one specific answer or question.

Daniel Brückner
I would expect the questions would want to be kept, so something more like: ... SelectMany(q => q.Answers.Select(a => new { A = a, Q = q }).Where(qa => qa.A.Name == "SomeName") would be a better fit.
Richard
You can always get back to the question with answer.Question - no need to introduce a anonymous type.
Daniel Brückner
@danbruc: No such property listed in the Q
Richard
You are right! I had some ORM in mind, but the question mentions only a class.
Daniel Brückner
+1  A: 

Use the SelectMany and First/FirstOrDefault (if you are needing one value)

List<Questions> questions = //initialization;
var someAnswer = questions.SelectMany(q=>q.Answers)
                          .First(a=>a.Name =="MyName");
Mike_G
A: 

It seems you could use something like this:

var query = from q in questions
            from a in q.Answers
            where a.Name == "Answer Name"
            select a;
bruno conde