首页 > 解决方案 > 在 c# 中将 linq 与包含嵌套 IEnumerable 的对象一起使用

问题描述

我有一个名为的对象ExportedPhotoresult exportedPhotoresult,其中包含一个 object Article article。这个 article 类型的对象包含另一个对象IEnumrable<ArticleDescriptionDetails> DescriptionDetails。最后一个具有三个 属性string Code和。string Valuebool Hidden

我正在尝试编写一个方法来返回exportedPhotoresultifDescriptionDetails.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
         )

但这显然是错误的。

标签: c#.net.net-core

解决方案


您可以测试Any()元素是否与表达式匹配;

return (exportedPhotoresult.Article.DescriptionDetails
        .Any(dd => !string.isNullorEmpty(dd.Code) && dd.Hidden == hidden))
    ? exportedPhotoresult
    : null;

但是由于您要返回父对象,因此我不会再尝试减少表达式。


推荐阅读