All four return a single element from a sequence; they differ in how they handle zero matches and multiple matches. First() - Returns the first matching element. - No match: throws InvalidOperationException ("Sequence contains no matching element"). - Multiple matches: returns the first one, no error. FirstOrDefault() - Returns the first matching element, or default (null for reference types, 0 for int) if none match. - Multiple matches: returns the first one. Single() - Returns the only matching element. - No match: throws InvalidOperationException. - More than one match: throws InvalidOperationException ("Sequence contains more than one matching element"). SingleOrDefault() - Returns the only matching element, or default if none match. - More than one match: still throws InvalidOperationException. Examples var orders = new List<Order> { new(1, "Asha"), new(2, "Ravi"), new(3, "Asha") }; orders.First(o => o.Customer == "Asha"); // Order 1 orders.FirstOrDefault(o => o.Customer == "Neha"); // null orders.Single(o => o.Id == 2); // Order 2 orders.SingleOrDefault(o => o.Id == 99); // null orders.Single(o => o.Customer == "Asha"); // throws: two matches orders.First(o => o.Customer == "Neha"); // throws: no matches When to use each - First: you expect at least one match and want the first (usually after OrderBy), and an empty result is a bug. - FirstOrDefault: a match is optional and several may exist; check for null. - Single: exactly one match must exist (for example a required configuration row); any other result is a data error. - SingleOrDefault: zero or one match is valid, but duplicates indicate a problem — lookups by a unique key such as email or primary key. Performance with EF Core - First and FirstOrDefault translate to SELECT TOP(1). - Single and SingleOrDefault translate to SELECT TOP(2), so EF can detect a second match. - Always add OrderBy before First when "first" must be deterministic. - For primary-key lookups, Find/FindAsync can return a tracked entity without querying the database. Defaults for value types can be misleading: FirstOrDefault on an int list returns 0 for no match, which may be a valid value. Use a nullable projection, or the .NET 6+ overload FirstOrDefault(predicate, defaultValue).
Ravindra Wadile · · 0 likes