Difference Between Single, SingleOrDefault, First, FirstOrDefault in Linq

By using Single() you indicate you know only one item will be returned, so LINQ gives you exactly one item, and not a collection with only one item in it.

var data = (from q in db.Items where q.Id == 1 select q).Single();

Where as SingleOrDefault() is useful if you're not sure if your query returns a record. When there isn't an item with an Id of 1, Single() will crash whereas SingleOrDefault() will return null when the item could not be found.

var data = (from q in db.Items where q.Id == 1 select q).SingleOrDefault();

Note : While writing a query one should make sure that it should not return more that One Item else Not it will throw an Exception

Exception : Sequence Contains more than One element.

By Using First() you Indicate that you want  first element of the sequence

Where as FirstOrDefault() is useful if you're not sure if your query returns any record.

Summary

FirstOrDefault() is for when zero or more results are expected to be present in the input collection and the call returns the first item if there are multiple results, Default if none.

SingleOrDefault() is for when zero or one result is expected in the input collection and the call returns the one result if exactly one result is present, Default if no results and exception if more than one result.

Comments

Popular posts from this blog

SQL Interview Questions and Answers

Generic Interface and Factory Pattern in C#

How to get device info IMEI programmatically in xamarin android