LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

Message par Clippy »

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

Re: LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

Message par Clippy »

Whenever you use [`SingleOrDefault`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault), you clearly state that the query should result in at most a *single* result. On the other hand, when [`FirstOrDefault`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault) is used, the query can return any amount of results but you state that you only want the first one.

I personally find the semantics very different and using the appropriate one, depending on the expected results, improves readability.
Répondre

Revenir à « .NET & C# »