linq问题:查询嵌套集合 [英] linq question: querying nested collections

查看:153
本文介绍了linq问题:查询嵌套集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题类,其公开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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆