What is the difference between First, FirstOrDefault, Single and SingleOrDefault?
Quick Answer
First — first match, throws if none. FirstOrDefault — first match or default(T) if none. Single — exactly one match, throws if zero or more than one. SingleOrDefault — zero or one, throws if more than one.
First gives you the first matching element and throws if there are none. FirstOrDefault returns null or the default instead of throwing. Single insists there's exactly one — it throws both if there are zero and if there are two or more. SingleOrDefault allows zero but still throws on more than one. I use Single for a lookup by primary key because it also asserts my uniqueness assumption, and FirstOrDefault with an OrderBy when several matches are fine and I just want the top one.
- Use
Single/SingleOrDefaultwhen the data model guarantees uniqueness (a lookup by primary key) — it also validates that assumption and fails loudly if it's violated. - Use
First/FirstOrDefaultwhen multiple matches are legitimate and you just want one (usually with anOrderBy). FirstOrDefaulton a reference type returnsnull; on a value type it returns0/false— check accordingly.- In EF,
Singlecan pull an extra row to check the “more than one” condition;FirstemitsTOP 1.