Advertisement
Intermediate C#, LINQ

What is the difference between First, FirstOrDefault and Single?

Short answer

First returns the first match or throws if none; FirstOrDefault returns default if none; Single expects exactly one and throws otherwise.

Save C# mock interview
Advertisement
AModel answer
First returns the first match or throws if none; FirstOrDefault returns default if none; Single expects exactly one and throws otherwise.
var a = xs.First(x => x.Id==1);
var b = xs.FirstOrDefault(x => x.Id==1);
var c = xs.Single(x => x.Id==1);
Real-world example
Use Single for a unique-key lookup where duplicates would indicate a data bug.