What is the point of FirstOrDefault

In entity framework when working with collections there is the option to use “.FirstOrDefault()” which essentially does a “SELECT TOP 1 *”.
However in any scenario where you are only ever expecting one record then “SingleOrDefault()” is ideal considering that an error is thrown when multiple items are present. If it does throw an error then it would make you aware your logic is fundamentally flawed in your app.

So realistically, why would someone use “FirstOrDefault()”?

When you want the edge of a list of data, say the oldest or newest in a time sorted dataset?

1 Like

Ah that would actually make sense, thanks! :slight_smile:

1 Like

Thre are multiple reasons. As you noted, what if you do have multiple items in your list, you may want the FirstOrDefault that matches a specific predicate, something like

mylist.FirstOrDefault(a => a.CoverageType == CoverageType.Liability)

So mylist contains a list of Coverages, but I only currently care about the CoverageType.Liability, which may or may not exist. I can’t use SingleOrDefault, as other CoverageTypes will also exist in this list.

I suppose my point is that when writing predicates, a lot of the time we expect to only get a single result back but it turns out that it isn’t specific enough. When using FirstOrDefault in this scenario, while most of the time works fine, sometimes we would get back unintended results.

Oh, well apart from better testing, I’m not sure there is an easy way to stop that. If you don’t write something specific enough to get the result you want… well… not much can resolve that. I guess using SingleOrDefault could, but it really depends on the circumstance of what is needed in that part of the code.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.