Many times in life we just want one thing. This is no exception for C# and when we are working with database entities.
When you want a single entity from a database, you will be given the choice of a few methods:
FirstOrDefault()
FirstOrDefault()
returns the first element that satisfies the predicate (aka “what we passed inside the function”). If nothing matches the predicate, the method will return null
(unless it’s a integer, then it will return 0
).
Stocks.FirstOrDefault(c => c.Symbol == "TSLA"); // TSLA with Id 1
Stocks.FirstOrDefault(c => c.Symbol == "PLTR"); // null
First()
First()
has stronger restrictions than FirstOrDefault()
. It will get the first element matching the element, but will throw an InvalidOperationExpception
if nothing is found.
Stocks.First(c => c.Symbol == "TSLA"); // TSLA with Id 1
Stocks.First(c => c.Symbol == "PLTR"); // System.InvalidOperationException
SingleOrDefault()
SingleOrDefault()
is similar to FirstOrDefault()
. The only difference is if more than one element matches the predicate it will throw an exception.
Stocks.SingleOrDefault(c => c.Symbol == "TSLA"); // TSLA with Id 1
Stocks.SingleOrDefault(c => c.Symbol == "MSFT"); // null
Stocks.SingleOrDEfault(c => c.Symbol == "PLTR"); // System.InvalidOperationException
Single()
Single()
is the most constrictive. It will return a result only if a single element matches the predicate solution. If no element is found or there is more than one matching element, it will throw an exception.
Stocks.SingleOrDefault(c => c.Symbol == "TSLA"); // TSLA with Id 1
Stocks.SingleOrDefault(c => c.Symbol == "MSFT"); // System.InvalidOperationException
Stocks.SingleOrDEfault(c => c.Symbol == "PLTR"); // System.InvalidOperationException
Which one is the “best”?
In most cases, we only need and should expect only one element. This is most common when we are searching by an Id. In the vast majority of cases, go with FirstOrDefault
.
First()
and Single()
are used when return null
will cause a cascading effect of NullReference errors or when accessing an object with null can be dangerous.
Happy Coding!