Both return one element or the default value (null for reference types) when nothing matches, but they have different expectations about how many elements may match. FirstOrDefault() - Returns the first matching element, or default if there are none. - If several elements match, it simply returns the first one — no error. - Stops as soon as it finds a match. SingleOrDefault() - Returns the only matching element, or default if there are none. - Throws InvalidOperationException if more than one element matches. - Must check that no second match exists, so it may scan further (in SQL, EF Core generates TOP(2) to detect duplicates). Examples var anyAdmin = users.FirstOrDefault(u => u.Role == "Admin"); // several admins are fine var user = users.SingleOrDefault(u => u.Email == email); // email must be unique When to use each - FirstOrDefault: when several matches are possible and any one (often with OrderBy) is acceptable — the latest order (orders.OrderByDescending(o => o.CreatedAt).FirstOrDefault()), the first available slot, or a quick existence lookup returning an element. - SingleOrDefault: when the data model guarantees at most one match (lookup by primary key or unique email), and you want the code to fail loudly if that assumption is broken by bad data. It acts as an assertion. Related methods - First(): throws if there are no matches. - Single(): throws if there are no matches or more than one. - Find() / FindAsync() in EF Core: looks up by primary key and checks the change tracker first, avoiding a database call if the entity is already tracked. - Any(): use it when you only need to know whether a match exists, rather than FirstOrDefault() != null. Performance with EF Core - FirstOrDefault generates SELECT TOP(1); SingleOrDefault generates SELECT TOP(2) to detect duplicates. Both are efficient when the filter uses an index. - Without OrderBy, "first" in SQL is not guaranteed to be stable; always add OrderBy when the choice matters. .NET 6+ also provides overloads with a custom default: FirstOrDefault(predicate, defaultValue). Summary: FirstOrDefault means "give me one if any exist"; SingleOrDefault means "there must be at most one — tell me if that is not true."
Ravindra Wadile · · 0 likes