Single()
/ SingleOrDefault()
|
First
() / FirstOrDefault()
|
Single()
- There is exactly 1 result, an exception is thrown if no result is returned
or more than one result.
SingleOrDefault()
– Same as Single(), but it can handle the null value.
|
First()
- There is at least one result, an exception is thrown if no result is
returned.
FirstOrDefault()
- Same as First(), but not thrown any exception or return null when there is
no result.
|
Single()
asserts that one and only one element exists in the sequence.
|
First()
simply gives you the first one.
|
When
to use
Use
Single / SingleOrDefault() when you sure there is only one record present in
database or you can say if you querying on database with help of primary key
of table.
|
When
to use
Developer
may use First () / FirstOrDefault() anywhere, when they required single
value from collection or database.
|
Single()
or SingleOrDefault() will generate a regular TSQL like "SELECT
...".
|
The
First() or FirstOrDefault() method will generate the TSQL statement like
"SELECT TOP 1..."
|
In
the case of First / FirstOrDefault, only one row is retrieved from the
database so it performs slightly better than single / SingleOrDefault. such a
small difference is hardly noticeable but when table contain large number of
column and row, at this time performance is noticeable.
|
What is the difference between FirstOrDefault and SingleOrDefault inlinq? | Linq Interview Question | ASP.NET Programmer Guide
Popular Tutorials
- Creating Cookie in ASP.NET MVC Action | Handling Cookies in ASP.NET MVC | Set Cookie Expiry in ASP.NET MVC | ASP.NET MVC Tutorial
- Generating Multiline TextBox or TextArea with @Html.EditorFor in ASP.NET MVC
- Generating Unique Token in C# | Generating Unique Token that Expires after 24 Hours in C# | C# Tutorial
- Drag & Drop File Upload In ASP.NET MVC Using dropzone js with Fallback Browser Support | ASP.NET MVC Tutorial
- Loading PartialView Via JQuery In ASP.NET MVC | Returning PartialView From ASP.NET MVC Action | ASP.NET MVC Tutorial
- How To Enable Role Manager Feature In ASP.NET MVC? | ASP.NET MVC Interview Question
- How To Add CSS Class And Custom Property in Html.TextBoxFor? | ASP.NET MVC | RAZOR
- Send and Receive SMS and MMS Messages Using Android 4.4 SMS API | Android Video Tutorial
- How to Get Browser Agent from ASP.NET Web API Controller? | ASP.NET Web API Tutorial
- How to Override the Common Route Prefix? | ASP.Net MVC Interview Question