简体   繁体   中英

Linq Lambda Where clause with in a where clause

I am trying to build a lambda expression with serval where clauses with in each other.

Items, webProperties and profiles are all lists. I am trying to find the one that contains a profile which is 3 level lists down. Actually all I am really trying to do is validate that it does exist.

 var x = AccountSummeriesResponse.items.Where(wp => wp.webProperties.Where(p => p.profiles.Where(a => a.id == profile ))).FirstOrDefault();

I am getting the following error.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'bool'

The probelm is Enumerable.Where returns IEnumarable<T> but the predicate of Where expects a boolen. You can use Any instead:-

var x = AccountSummeriesResponse.items
           .Where(wp => wp.webProperties.Any(p => p.profiles.Any(a => a.id == profile )))
           .FirstOrDefault();

Also, you can replace the Where with FirstOrDefault like this:-

 var x = AccountSummeriesResponse.items
         .FirstOrDefault(wp => wp.webProperties.Any(p => p.profiles
                                               .Any(a => a.id == profile )));

That's because delegate( Predicate ) inside the where clause needs to return bool and you are returning IEnumerable( Where(p => p.profiles.Where(a => a.id == profile )) ) so reporting a compilation error.

Instead make a use of Any extension method if you are looking for whether exist in the collection kind of thing..

var x = AccountSummeriesResponse.items.Where(wp => wp.webProperties.Any(p => p.profiles.Any(a => a.id == profile ))).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM