C# linq 问题:查询嵌套集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/721395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:28:35  来源:igfitidea点击:

linq question: querying nested collections

c#.netlinqcollectionslinq-to-xml

提问by kitsune

I have a Questionclass that has public List property that can contain several Answers.

我有一个Question类,它具有可以包含多个Answers 的公共 List 属性。

I have a question repository which is responsible for reading the questions and its answers from an xml file.

我有一个问题存储库,负责从 xml 文件中读取问题及其答案。

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.

所以我有一个问题集合(列表),每个问题对象都有一个答案集合,我想使用 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.

我可以用 foreach 来做,但我想知道是否有一种纯粹的 Linq 方式,因为我正在学习它。

采纳答案by Daniel Brückner

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.

事实上,你会得到答案或问题的收藏,你将不得不使用First()FirstOrDefault()Single(),或SingleOrDefault()根据您的需要得到一个明确的答案或问题。

回答by ybo

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

回答by Mike_G

Use the SelectMany and First/FirstOrDefault (if you are needing one value)

使用 SelectMany 和 First/FirstOrDefault(如果您需要一个值)

List<Questions> questions = //initialization;
var someAnswer = questions.SelectMany(q=>q.Answers)
                          .First(a=>a.Name =="MyName");

回答by bruno conde

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;