what kind of data FirstOrDefault or SingleOrDefault will return.
suppose my query return 3 record like
empid ename salary
----- ----- ------
1 joy 1500
2 rob 4500
3 jen 6500
so if we use FirstOrDefault or SingleOrDefault then what kind of resultset i will get. please explain with example. thanks
Element Operators: First & FirstOrDefaultReturns the first element of a collection, or the first element that satisfies a condition. FirstOrDefault. Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
Use Single() when you are sure that the query must return only one record, and use SingleOrDefault() when a query returns the only element from the sequence, or a default value if the sequence is empty.
The SingleOrDefault() method does the same thing as Single() method. The only difference is that it returns default value of the data type of a collection if a collection is empty, includes more than one element or finds no element or more than one element for the specified condition.
The major difference between First() and FirstOrDefault() is First will throw an exception when there are no results and FirstOrDefault won't. In fact, FirstOrDefault will simply return the null value (reference types) or the default value of the value type.
| 0 values | 1 value | > 1 value
FirstOrDefault | Default | First value | First value
SingleOrDefault | Default | First value | Exception
And to extend this table to the entire set:
| 0 values | 1 value | > 1 value
First | Exception | First value | First value
FirstOrDefault | Default | First value | First value
Single | Exception | First value | Exception
SingleOrDefault | Default | First value | Exception
Last | Exception | Last value | Last value
LastOrDefault | Default | Last value | Last value
And here's another version with some concrete values to make it clearer:
| [] | [1] | [1,2,3]
First | Exception | 1 | 1
FirstOrDefault | 0 | 1 | 1
Single | Exception | 1 | Exception
SingleOrDefault | 0 | 1 | Exception
Last | Exception | 1 | 3
LastOrDefault | 0 | 1 | 3
SingleOrDefault will return exception because it wait to get one record or no record and FirstOrDefault will return the first record (1 joy 1500)
you can use SingleOrDefault when your where contains a condition that will surly return on record in you case - where empid == 1
obviously you want only one DB record with the ID 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With