Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding .Single()

Tags:

c#

asp.net

[This is a really tough one to Google.]

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?

thx

In the time since the OP i've learned a bit more about usage that'll help other hits to this question:

var option = options.OfType<AdditionalLocationsOption>().SingleOrDefault();
if (option != null){
...stuff
}
like image 568
justSteve Avatar asked Jun 17 '26 20:06

justSteve


1 Answers

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.

If you know that the collection has exactly one element, this code is simpler than a foreach loop and makes its intentions clearer.

like image 90
SLaks Avatar answered Jun 19 '26 10:06

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!