我有一个的问题类有一个可以包含多个回答公众列表属性
I have a Question class that has public List property that can contain several Answers.
我有一个问题库,负责从XML文件读取的问题和答案。
I have a question repository which is responsible for reading the questions and its answers from an xml file.
所以,我有问题(列表),每个问题的对象有答案的集合,我想查询的问题的这个集合的答案(即由它的名字)使用LINQ的集合。我不知道如何正确地做到这一点。
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.
我可以用一个foreach做,但我想知道是否有纯粹的LINQ的方式,因为我学习它。
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.
要找到一个答案。
questions.SelectMany(q => q.Answers).Where(a => a.Name == "SomeName")
要找到答案的问题。
question.Where(q => q.Answers.Any(a => a.Name == "SomeName"))
事实上,你会得到答案或问题的集合,你将不得不使用一()
, FirstOrDefault()
,单()
或的SingleOrDefault()
根据您的需要得到一个明确的答案或问题。
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.