Home > DeveloperSection > Forums > Understanding .Single()
Chintoo Semi

Total Post:135

Posted on    August-23-2014 7:25 AM

 C# C# 

 1 Reply(s)
 829  View(s)
Rate this:

Browsing sample code I'm seeing a usage I don't understand:

var orderRow = order.Rows.Single();

Rows is an enumerable and usually one would iterate using a foreach loop. Is the .Single a workaround for cases where, for whatever reason, the foreach can't be (or need not) be used?

var option = options.OfType<AdditionalLocationsOption>().SingleOrDefault();

if (option != null){



Sumit Kesarwani

Total Post:378

Posted on    August-23-2014 8:56 AM

Hi Chintoo, 

LINQ's Single method returns the single element in a collection.

This would be written in Rows is known to contain exactly one row.

If it's empty, or if it has more than one row, an exception will be thrown.

Don't want to miss updates? Please click the below button!

Follow MindStick