Mou
Mou

Reputation: 16282

Regarding FirstOrDefault or SingleOrDefault

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

Upvotes: 5

Views: 4208

Answers (3)

Richard Szalay
Richard Szalay

Reputation: 84744

                | 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

Upvotes: 35

kleinohad
kleinohad

Reputation: 5912

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

Upvotes: 3

ghimireniraj
ghimireniraj

Reputation: 397

FirstOrDefault will return you the first element and the default value (default value for value type and null for reference type) the element if no elements are present.

SingleOrDefault will return the the element if only one is present. Default if none are present and throws an exception if more than one elements are in your query.

In your case FirstOrDefault will return the first element. And SingleOrDefault will throw an exception.

Upvotes: 3

Related Questions