Posts

Showing posts from February, 2015

LINQ First vs FirstOrDefault vs Single vs SingleOrDefault

Below is a chart explaining the difference between them and examples of each scenario. First() FirstOrDefault ( ) Single ( ) SingleOrDefault ( ) Description Return first element of the sequence elements Return first element of the sequence elements or default value if no element is found Return a single element of a sequence Return a single element of a sequence, or a default value if that element is not found\ Exception Thrown when There are no elements in the result Only if the source is null There are 0 or more than 1 elements in the result There is more than one element in the result When to use When more than 1 element is expected and you want only the first When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty If exactly 1 element is expected not 0 or more than 1 When 0 or 1 element is expected Example First, we create an Employee table for querying. We will test with different ...