Methods returning single item

Methods - Extract a single element

First() method

Intuitively enough, this extracts the first element in the sequence

var doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.First();

Console.WriteLine(whatsThis);
Console.ReadKey();

Conditionally extract the first element

List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.First(val => val > 2.1);

Console.WriteLine(whatsThis);
Console.ReadKey();

What happens if it was val > 2.3 ?

Single() method

Conditionally extract single element

List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.Single(val => val > 2.2);

What happens if it was val > 2.1 ?

FirstOrDefault() method

What do you think this call to FirstOrDefault() would return?

var doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.FirstOrDefault(val => val > 2.3);

Console.WriteLine(whatsThis);
Console.ReadKey();

SingleOrDefault() method

SingleOrDefault() is a bit different from the others. If there is no element in the list that meets the criteria, then a default value is returned. If more than one value meets the criteria, then SingleOrDefault() still throws an exception, just like the Single() method.

With this in mind, what do you think this would do?

List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.SingleOrDefault(val => val > 2.1 && val <= 2.3);

Console.WriteLine(whatsThis);
Console.ReadKey();

Can you try these for your own collection of other data types like string?

Last updated