linq question: querying nested collections

C#.NetLinqCollectionsLinq to-Xml

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

To find an answer.

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

To find the question of an answer.

questions.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.

Solution 2 - C#

from question in Questions
from answer in question.Answers
where answer.Name == something
select question // or select answer

Solution 3 - C#

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");

Solution 4 - C#

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkitsuneView Question on Stackoverflow
Solution 1 - C#Daniel BrücknerView Answer on Stackoverflow
Solution 2 - C#yboView Answer on Stackoverflow
Solution 3 - C#Mike_GView Answer on Stackoverflow
Solution 4 - C#bruno condeView Answer on Stackoverflow