Using C# LINQ - A Practical Overview
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Methods - Extract a single element
These LINQ methods can be used to extract a single element from an IEnumerable<T>
sequence.
NOTE: All four of the methods in this lesson throw an exception if they can't find an appropriate element to return. Only use them if you are absolutely certain that an element exists for them to return. You could
catch
the exception (and probably should to handle true error conditions) but if you expect that these may reasonably fail, you should use theOrDefault
variants instead. We will go over those methods in a later lesson.
First() method
Intuitively enough, this extracts the first element in the sequence. The data type of the value returned depends on the type of T
in the IEnumerable<T>
that the method is invoked on. If it is a sequence of int
, then First()
will return an int
.
For example:
List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.First();
Looking at this code, what do you think the First()
method call would return?
Last() method
Hmm.... What do you think the Last()
in this code would return?
List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.Last();
ElementAt() method
Try this one. What would the ElementAt(2)
call return in this code snippet?
List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.ElementAt(2);
Single() method
Single()
is an interesting method. You call it when you are expecting that there is only a single element in the sequence. If there is more than one element, or if there are no elements, then Single()
will throw an exception.
With this in mind, what do you think this would return?
List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.Single();