linq问题:查询嵌套集合 [英] linq question: querying nested collections
问题描述
我有一个问题类,其公开List属性可以包含多个答案。
一个问题库,负责从一个xml文件中读取问题及其答案。
所以我有一个问题集合的答案,我想使用Linq查询这个问题集合的答案(即通过其名称)。我不知道如何正确地这样做。
我可以做一个foreach,但我想知道是否有一个纯Linq的方式,因为我'
<$ p $
p> questions.SelectMany(q => q.Answers).Where(a => a.Name ==SomeName)
要找到答案的问题。
(q => q.Answers.Any(a => a.Name ==SomeName))
$ b b
事实上,你会收到回答或问题的集合,你必须使用 First()
, FirstOrDefault()
, Single()
或 SingleOrDefault()
,取决于您的需要得到一个具体的答案或问题。
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.
To find an answer.
questions.SelectMany(q => q.Answers).Where(a => a.Name == "SomeName")
To find the question of an 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.
这篇关于linq问题:查询嵌套集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!