C# › LINQ

What is the difference between First(), FirstOrDefault(), Single(), and SingleOrDefault()?

Intermediate

Answer

First() returns the first matching element or THROWS if none exists; FirstOrDefault() returns the first match or the type's DEFAULT value (like null or 0) if none exists; Single() requires EXACTLY ONE match (throws if zero OR more than one); SingleOrDefault() requires ZERO or ONE match (throws only if MORE than one), returning default for zero.
var numbers = new List<int> { 1, 2, 3 };
int first = numbers.First(n => n > 1);              // 2
int? firstOrNone = numbers.FirstOrDefault(n => n > 10); // 0 (default for int)
int single = numbers.Single(n => n == 2);            // 2 -- exactly one match required
Real-world example Using Single() to enforce that a lookup by unique ID returns EXACTLY one record, catching data integrity bugs if it somehow doesn't.

Common follow-ups: Why might using Single() instead of First() actually help CATCH a subtle data bug rather than just being 'more strict for no reason'?