Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Single vs First

Tags:

.net

linq

People also ask

What is difference between first and single in LINQ?

Single() asserts that one and only one element exists in the sequence. First() simply gives you the first one. Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.

What is difference between first and FirstOrDefault in LINQ?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data. First() will throw an exception if there is no result data, as you can see below.

Which is faster SingleOrDefault or FirstOrDefault?

c# - FirstOrDefault is signicantly faster than SingleOrDefault while viewing ANTS profiler - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What is single () in C#?

C# Single() Method CsharpProgrammingServer Side Programming. Get only a single element of a sequence using the Single() method. Let's say we have a string array with only one element. string[] str = { "one" }; Now, get the element.


If you're expecting a Single record, it's always good to be explicit in your code.

I know others have written why you use one or the other, but I thought I'd illustrate why you should NOT use one, when you mean the other.

Note: In my code, I will typically use FirstOrDefault() and SingleOrDefault() but that's a different question.

Take, for example, a table that stores Customers in different languages using a Composite Key ( ID, Lang ):

DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).First();

This code above introduces a possible logic error ( difficult to trace ). It will return more than one record ( assuming you have the customer record in multiple languages ) but it will always return only the first one... which may work sometimes... but not others. It's unpredictable.

Since your intent is to return a Single Customer use Single();

The following would throw an exception ( which is what you want in this case ):

DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).Single();

Then, you simply hit yourself on the forehead and say to yourself... OOPS! I forgot the language field! Following is the correct version:

DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 && c.Lang == "en" ).Single();

First() is useful in the following scenario:

DBContext db = new DBContext();
NewsItem newsitem = db.NewsItems.OrderByDescending( n => n.AddedDate ).First();

It will return ONE object, and since you're using sorting, it will be the most recent record that is returned.

Using Single() when you feel it should explicitly always return 1 record will help you avoid logic errors.


Single will throw an exception if it finds more than one record matching the criteria. First will always select the first record from the list. If the query returns just 1 record, you can go with First().

Both will throw an InvalidOperationException exception if the collection is empty. Alternatively you can use SingleOrDefault(). This won't throw an exception if the list is empty


Single()

Returns a single specific element of a query

When Use: If exactly 1 element is expected; not 0 or more than 1. If the list is empty or has more than one element, it will throw an Exception "Sequence contains more than one element"

SingleOrDefault()

Returns a single specific element of a query, or a default value if no result found

When Use: When 0 or 1 elements are expected. It will throw an exception if the list has 2 or more items.

First()

Returns the first element of a query with multiple results.

When Use: When 1 or more elements are expected and you want only the first. It will throw an exception if the list contains no elements.

FirstOrDefault()

Returns the first element of a list with any amount of elements, or a default value if the list is empty.

When Use: When multiple elements are expected and you want only the first. Or the list is empty and you want a default value for the specified type, the same as default(MyObjectType). For example: if the list type is list<int> it will return the first number from the list or 0 if the list is empty. If it is list<string>, it will return the first string from the list or null if the list is empty.


If you don't specifically want an exception thrown in the event that there is more than one item, use First().

Both are efficient, take the first item. First() is slightly more efficient because it doesn't bother checking to see if there is a second item.

The only difference is that Single() expects there to be only one item in the enumeration to begin with, and will throw an exception if there are more than one. You use .Single() if you specifically want an exception thrown in this case.