1

eI need to select a particular single data element from first row ordered descending by date. Please specify the differences between the following keywords.

  • First
  • FirstOrDefault
  • singleOrDefault

Also need the precedence/order and usage rules of placing Orderby, where & select in Linq ORM Query. It would be much helpful if answer could be clear & descriptive.

Thanks in advance

Shalem
  • 1,446
  • 2
  • 22
  • 47

1 Answers1

4

A quick Google gives you the following Questions which address your question:

You might also find the following article useful as it goes into each method:

As stated in the answers, the names do give it away (to those familiar), but here's a quick overview:

First

Will return the first entry in a collection (one or more results returned), will throw an exception if no records returned.

FirstOrDefault

Will return the first entry in a collection (one or more results returned), will return the appropriate default object if no records returned

SingleOrDefault

This one isn't really the same as the previously mentioned functions, it will return the result only if only one record is returned, otherwise will return the appropriate default object.

I tend to use First if I know that my results will always return "something", I use FirstOrDefault when I just want the first element but know that sometimes the query might return nothing. I've yet to personally use SingleOrDefault but it should only be used where your query is only ever going to return one row and that returned results should be ignored if more than one result exists.

Community
  • 1
  • 1
talegna
  • 2,407
  • 2
  • 19
  • 22