Find vs FirstOrDefault

7/3/2022

In C# .NET, the .Find() and .FirstOrDefault() functions act similarly: Each return either a matching object, or null. These are both opposed to the .First() call, which will return either the first matching object, or throw an exception.

DbSet Find()

Although there is a .Find() on the List<> class, I want to focus on Entity Framework here. The DbSet class has a .Find() which searches by Primary Key. So although you can search by primary key using .FirstOrDefault(), it's certainly best to use a function written specifically for that. Additionally, this has performance benefits. If the key is already being tracked by the context (and therefore in memory), it avoids unnecessary database queries and returns the object which is already tracked.

Given that, although .FirstOrDefault() is often used out of habit, if you're searching by primary key, instead of doing this:

 
var book = context.Books.FirstOrDefault(b => b.Id == 123);   

Use this:

 
var book = context.Books.Find(123);   

BTW, this is one of those articles I mostly wrote for me as a reminder...


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET
  • T-SQL
  • HTML/CSS
  • JavaScript/jQuery
  • .NET 8
  • ASP.NET/MVC
  • Xamarin/MAUI
  • WPF
  • Windows 11
  • SQL Server 20xx
  • Android
  • XBox
  • Arduino
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking