Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...