Thursday, November 2, 2017

C# LINQ : SingleOrDefault() Vs. FirstOrDefault()

LINQ provides the operators like Single (), SingleOrDefault(), First() and FirstOrDefault(), they select a specific record from collection.SingleOrDefault() and FirstDefault() returns NULL or Default Value if there is no matching record found.


here is a list of customers :
 List<Customer>Customers = new List<Customer>
            {
                 new Customer { CustomerID = 1, Name= “Herry” },
                 new Customer { CustomerID = 2, Name=”Tom” }
            };

Select record by using FirstOrDefault() method
  Customer customer = Customers.FirstOrDefault(x => x.CustomerID = 1)

Select record by using SingleOrDefault() method
                Customer customer = Customers.SingleOrDefault(x => x.CustomerID = 2);

SingleOrDefault() vs FirstOrDefault()
  • SingleOrDefault() throw exception if we have more than one matching records, and FirstOrDefault() returns the first matching record in sequence.
  • Both SingleOrDefault() and  FirstOrDefault() return default value or NULL, If no matching record found.
  • FirstOrDefault() generates the TSQL statement "SELECT TOP 1..." and SelectOrDefault() generates regular TSQL statement "SELECT ..”
  • In Performance, FirstOrDefault() is usually faster than SingleOrDefault(). The FirstOrDefault() doesn’t care about record uniqueness and amount of record

Recommendations: if you sure, the query should result in at most a single result, you should use SingleOrDefault(), and on other side if query return any number of results, you should use FirstOrDefault() method.

Thanks for visiting!!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...