Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117261

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'

Upvotes: 2

Views: 7788

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21825

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 )));

Upvotes: 12

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

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();

Upvotes: 0

Related Questions