Lx2pwn
Lx2pwn

Reputation: 323

use linq with object that contains nested IEnumerable in c#

I have an object called ExportedPhotoresult exportedPhotoresult which contains an object Article article. This object of type article contains another object IEnumrable<ArticleDescriptionDetails> DescriptionDetails. This last one has three property string Code, string Value and bool Hidden.

I'm tring to write a method to return an exportedPhotoresultif DescriptionDetails.Code is not empty or null, and DescriptionDetails.Codeis equals to 'hidden'

I write this code

foreach (var dd in exportedPhotoresult.Article.DescriptionDetails)
     if (!dd.Code.isNullorEmpty() && dd.Hidden == hidden)
        return exportedPhotoresult;
return null

Is it possibile re-write this code using Linq ?

I tried in this way

return exportedPhotoresult.Article.DescriptionDetails
        .Where( x=> 
            !string.IsNullOrEmpty(x.Code) && 
            x.Hidden == hidden
         )

But it's obviusly wrong.

Upvotes: 0

Views: 162

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11120

You can test if Any() element matches the expression;

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

But since you are returning the parent object, I wouldn't try to reduce the expression any futher.

Upvotes: 1

Related Questions