c# - 在 c# 中将 linq 与包含嵌套 IEnumerable 的对象一起使用
问题描述
我有一个名为的对象ExportedPhotoresult exportedPhotoresult
,其中包含一个 object Article article
。这个 article 类型的对象包含另一个对象IEnumrable<ArticleDescriptionDetails> DescriptionDetails
。最后一个具有三个 属性string Code
和。string Value
bool Hidden
我正在尝试编写一个方法来返回exportedPhotoresult
ifDescriptionDetails.Code
不为空或 null,并且DescriptionDetails.Code
等于“隐藏”
我写这段代码
foreach (var dd in exportedPhotoresult.Article.DescriptionDetails)
if (!dd.Code.isNullorEmpty() && dd.Hidden == hidden)
return exportedPhotoresult;
return null
是否可以使用 Linq 重新编写此代码?
我试过这样
return exportedPhotoresult.Article.DescriptionDetails
.Where( x=>
!string.IsNullOrEmpty(x.Code) &&
x.Hidden == hidden
)
但这显然是错误的。
解决方案
您可以测试Any()
元素是否与表达式匹配;
return (exportedPhotoresult.Article.DescriptionDetails
.Any(dd => !string.isNullorEmpty(dd.Code) && dd.Hidden == hidden))
? exportedPhotoresult
: null;
但是由于您要返回父对象,因此我不会再尝试减少表达式。
推荐阅读
- laravel-5 - Laravel 背包:用于多态关系的 CRUD
- google-analytics - '平均。Google Analytics 上的“页面停留时间”为零
- python - Tensorflow 估计器:不同的纪元数给出相同的结果
- xml - 如何按xslt中的属性值对xml文件进行排序?
- java - Selenium chromedriver 无法正确关闭
- docker - Docker 容器中的 Flutter 在 Jenkins 中失败,但在本地失败
- regex - 为什么这不计算字符串末尾的 CRLF?
- python - 扩展部署词汇
- coldfusion - ColdFusion 2016 修改了代码分析器返回的 CFloop 标签的用法
- xamarin - 如何为启动画面做 Xamarin.UITest?