4

Can any one please explain this lines of code?

bool status = datacontext.tblTransactionDetails.Where(x => x.AdvertID == app.AdvertID && x.IsActive == true).FirstOrDefault() == null ? false : true;
leppie
  • 115,091
  • 17
  • 196
  • 297

1 Answers1

6

It means take the first item from the collection where AdvertID == app.AdvertID && IsActive == true. If it's null return false, otherwise return true.

The ? : syntax is known as the ternary operator and is used as a shorthand for if/else.

Instead you could use

.Any(x => x.AdvertID == app.AdvertID && x.IsActive == true) 

this returns true if any meet the conditions, otherwise false.

The full line of code would be:

bool status = datacontext.tblTransactionDetails.Any(x => x.AdvertID == app.AdvertID && x.IsActive == true);
Steve
  • 2,950
  • 3
  • 21
  • 32
  • 3
    x.IsActive == true could be shortened to x.IsActive – Vincent Dec 02 '14 at 11:30
  • I think better is to do .count? – Sandip Bantawa Dec 02 '14 at 12:27
  • @brykneval How would you filter on the condition beforehand? But yes, generally the Count field/property would be quicker, but we are talking ridiculous levels of micro optimisation here. Based on the filtering requirements, using .Any() is semantically much better, and importantly it is very readable and concise. – Steve Dec 02 '14 at 12:53
  • var countData = datacontext.tblTransactionDetails.Count(x => x.AdvertID == app.AdvertID && x.IsActive); and then check accordingly? – Sandip Bantawa Dec 02 '14 at 14:02
  • @brykneval That is less efficient than using .Any(). Your way will enumerate every item in the collection to check the predicate. Using .Any() will stop enumerating when it finds the first item that matches the predicate. – Steve Dec 02 '14 at 14:10
  • @DarrenYoung Yes it seems like and I too thought that way but it actually might not be please see this link: http://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0 – Sandip Bantawa Dec 02 '14 at 14:19
  • Even this: http://stackoverflow.com/questions/17890645/comparing-performance-of-generated-quries-for-any-vs-count-in-entity-framewo – Sandip Bantawa Dec 02 '14 at 14:23
  • @brykneval You are getting confused with the Count() method and the Count property. Some collections keep track of their item count in a property, some don't but you can use a Count() method. Accessing the property is quicker than .Any() which in turn is generally quicker than the Count() method. – Steve Dec 02 '14 at 14:47
  • @brykneval Have a look here http://stackoverflow.com/questions/4098186/list-count-vs-count-which-one-and-why – Steve Dec 02 '14 at 14:49
  • my above is related to linq, isn't it? and it gets mapped to sql and with laterversion of sql, I guess 2008 onward can be replaced with merge which is twice faster and I guess even better query mapped is with FirstOrDefault than .Any – Sandip Bantawa Dec 02 '14 at 15:01