ediblecode
ediblecode

Reputation: 11971

Resolving bool from linq query

I have a property OnHomePage which is a bool.

I am trying to set this value based on whether a result is returned from a linq query or not. Obviously I could write an external method to determine whether the result of my query is null or whether it holds a value but I am hoping there is a better way for it to be done in one line.

Here is my current line of code as it stands:

OnHomePage = im.PageImages.Select(p => p.ImageId == im.Id 
                                      && p.Page.PageName == "/Home")

Upvotes: 1

Views: 255

Answers (4)

Omar
Omar

Reputation: 16623

As said other users you can use Any():

OnHomePage = im.PageImages.Any(p => p.ImageId == im.Id 
                                      && p.Page.PageName == "/Home");

Or another solution could be use Exists():

OnHomePage = im.PageImages.ToList().Exists(p => p.ImageId == im.Id 
                                          && p.Page.PageName == "/Home");

Here is an interesting answer explain the differences.

PS:

In behaviour, these are identical.

Upvotes: 0

Servy
Servy

Reputation: 203809

OnHomePage = im.PageImages.Where(p => p.ImageId == 
  im.Id && p.Page.PageName == "/Home").Any();

Upvotes: 2

dtb
dtb

Reputation: 217401

You can use the Any Extension Method to determine if a query gives any result or not:

OnHomePage = im.PageImages.Any(p => p.ImageId == im.Id 
                                   && p.Page.PageName == "/Home");

Upvotes: 4

Jon
Jon

Reputation: 437804

You should simply wrap up the query with .Any:

OnHomePage = im.PageImages.Where(p => p.ImageId == im.Id 
                                  && p.Page.PageName == "/Home")
                          .Any();

Or, just use the other overload of Any directly in the first place:

OnHomePage = im.PageImages.Any(p => p.ImageId == im.Id 
                                  && p.Page.PageName == "/Home");

Upvotes: 3

Related Questions