1

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")
ediblecode
  • 10,724
  • 16
  • 62
  • 111
  • 1
    everybody answered without thinking , DOES your bool should return true if at least 1 is true , or ALL of them ....? – Royi Namir May 01 '12 at 13:57
  • 1
    @RoyiNamir: I don't think that's fair to say. Speaking just for myself, I did pay attention to *"whether a result is returned from a linq query or not."* That's `Any`. – Jon May 01 '12 at 13:58
  • @jon my bad. Didnt see ( unless fast-edited...) – Royi Namir May 01 '12 at 14:03

4 Answers4

4

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");
dtb
  • 198,715
  • 31
  • 379
  • 417
  • "Any" is especially good for this since it's short circuited and will stop iterating through the items when it finds a match. – bryanbcook May 01 '12 at 13:57
  • 2
    @bryanbcook: So does `.Where(..).Any()`. `.Any(..)` may result in a more efficient translation to SQL though, depending on the LINQ provider. – dtb May 01 '12 at 13:58
  • 2
    @bryanbcook This is likely an IQueryable, not an Enumerable, so that depends entirely on the query provider. – Servy May 01 '12 at 13:59
3

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");
Jon
  • 396,160
  • 71
  • 697
  • 768
  • 2
    need to change the `Select` to a `Where` in the first query. The second query is fine. – Servy May 01 '12 at 13:57
2
OnHomePage = im.PageImages.Where(p => p.ImageId == 
  im.Id && p.Page.PageName == "/Home").Any();
Servy
  • 193,745
  • 23
  • 295
  • 406
0

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.

Community
  • 1
  • 1
Omar
  • 14,695
  • 8
  • 40
  • 61