Monday, August 12, 2013

LINQ- Difference between Single and SingleOrDefault- Single vs SingleOrDefault

In today's development, we all are frequently users of LINQ. So In this post and some incoming posts, I will try to explain about some LINQ's extension methods that seems trivial, but can really helpful to improve your code by making it easier.

Here, In this post I am going to explain you about Single and SingleOrDefault method and difference between these methods.

You can find some other useful topics and posts here. Below is a chart explaining about Single() and SingleOrDefault(). You can easily differentiate these methods from this chart. I have also given examples of each method.



Description

When thrown Exception

When to Use

Single()

Returns only item of a sequence.

There is 0 or more than 1 elements in the result.

If exactly 1 element is expected, not 0 or more than 1.

SingleOrDefault()

Returns a single, specific element of a sequence, or a default value if that element is not found.

There is more than 1 element in the result.

If 0 or 1 element are expected, not more than 1.

Examples

We have an UserInfo table, which have some records as shown below.
Single and SingleorDefault in LINQ
We will use thee above table to querying for Single() and SingleOrDefault(). Here I have used LINQ to SQL.

Single()


DataClasses1DataContext dc = new DataClasses1DataContext();

Statement

Expected Result

Actual Result

var result = dc.UserInfos.Single(x => x.ID == 1);

There is only one record where ID== 1. Should return this record

ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

var result = dc.UserInfos.Single(x => x.FName == "Rahul");

There are multiple records where FName == "Rahul". An error should be occur.

InvalidOperationException: Sequence contains more than one element

var result = dc.UserInfos.Single(x => x.ID ==13);

There is no record with ID== 13. An error should be occur.

InvalidOperationException: Sequence contains no elements

SingleOrDefault()

DataClasses1DataContext dc = new DataClasses1DataContext();

Statement

Expected Result

Actual Result

var result = dc.UserInfos.SingleOrDefault(x => x.ID == 1);

There is only one record where ID== 1. Should return this record

ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

var result = dc.UserInfos.SingleOrDefault(x => x.FName == "Rahul");

There are multiple records where FName == "Rahul". An error should be occur.

InvalidOperationException: Sequence contains more than one element

var result = dc.UserInfos.SingleOrDefault(x => x.ID ==13);

There is no record with ID== 13. An error should be occur.

null

I hope this will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome

No comments:

Post a Comment

^ Scroll to Top