FirstOrDefault and SingleOrDefault in ASP.NET

This is a small, simple and very basic Tip. But for beginners like me can still make silly mistake while using these two gems during LINQ to SQL. The exceptions generated by these really frustrates beginners if they are not concerned about the results they expect from their queries.

Here is the basic difference that might help us during keying our queries.

SingleOrDefault

FirstOrDefault

  • As the name suggests, returns a SINGLE
    the FIRST element from the list.

    or specific element. Else a default value if element

    the specified element is not found.

This returns


or default value if no such specified

found.

  • Here, Exception is thrown when more than
    element

    one element is present
    source is NULL.

Here, when there is no


in the result set and or the
we expect a single element.

  • It should be used when 0/1 elements are
    than one element is

    expected from our queries.
    first element.

It should be used when more


expected and we want only the


Examples are the best way to express. Lets take one.

Suppose we have a Books table for querying, with BookId as PrimaryKey || BookName as Required and AuthorName as Nullable.

BookId

BookName

AuthorName

1

Asp.Net MV

Adam Freeman

2

C# 2008

Andrew Troelsen

3

SqlServer 2012

Ross Mistry

4

HTML5/CSS3

Andrew Troelsen

5

KnockOut

NULL


SingleOrDefault():

" Books.SingleOrDefault(b=> b.BookId== 2) "----This block of Code returns the C# 2008 as the BookId is unique and single.

"Books.SingleOrDefault(b=> b.AuthorName== "Andrew Troesen")" ----This block of Code returns "InvalidOperationException: Sequence contains more than one element".


FirstOrDefault():

"Books.FirstOrDefault(b=> b.AuthorName== "Andrew Troesen")"----Though there are two elements with author Andrew Troesen,it returns the oldest one or the BookName:-C# 2008.

So, to avoid exception and handling them, It's better to know how we want our queries to behave and what results we expect from our queries.

This small thing has helped me a lot. Hope this helps beginners.

Happy coding.

Invincix Solutions Private limited
Every INVINCIAN will keep their feet grounded, to ensure, your head is in the cloud