David Klempfner
Oct 19, 2024

That's a good point, didn't even think about that.

One thing that is interesting to note is that if you call SingleOrDefault() on an IQueryable, it does "SELECT TOP 2...." on the DB side and only returns two results from the entire collection back to .NET, which I assume behind the scenes, just checks if there are two results and then throws an exception.

So in this particular case, it doesn't need to iterate through the whole collection (although SQL server probably has to behind the scenes).

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

David Klempfner
David Klempfner

Written by David Klempfner

I’m a software developer who is passionate about learning how things work behind the scenes.

Responses (1)

Write a response

Yeah, on an IQueryable, where the work is being done by the database, .NET only needs 2 results to prove it isn't a Single. The database, hopefully, should be properly indexed, making the TOP 2 more efficient than a full-table scan. Of course, if…

--