Saturday, 30 December 2017

SingleOrDefault Vs FirstOrDefault

 SingleOrDefault() Vs. FirstOrDefault() in LINQ Query


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 statment like "SELECT TOP 1..."
In the case of Fist / 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.

Related Posts:

  • IEnumerable vs IQueryable Many  developers gets confused between IEnumerable and IQueryable. When it comes to writing code, both looks very similar. However the… Read More
  • Lazy Loading and Eager Loading ~Difference between Lazy Loading and Eager Loading~ In LINQ and Entity Framework, you have Lazy Loading and Eager Loading for loading the related en… Read More
  • LINQ vs Stored Procedure Comparing LINQ with Stored ProcedureLINQ provide you common query syntax to query various data sources like SQL Server, Oracle, DB2, WebServices, XML… Read More
  • LINQ/LAMBDA Query Example How to get the Value of attribute from XML using XDocument class string inputXml = @"<?xml version='1.0' encoding='UTF-8'… Read More
  • LINQ LINQ is a technique for querying data from any Datasource. data source could be the collections of objects, database or XML files. We can easily retr… Read More

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives