linq 问题:查询嵌套集合 [英] linq question: querying nested collections
问题描述
我有一个 Question 类,该类具有可以包含多个 答案 的公共 List 属性.
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")
找到答案的问题.
questions.Where(q => q.Answers.Any(a => a.Name == "SomeName"))
事实上你会得到答案或问题的集合,你必须使用First()
、FirstOrDefault()
、Single()
或 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.
这篇关于linq 问题:查询嵌套集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!