Back
Close

Using C# LINQ - A Practical Overview

player_one
1638.1K views

Methods - Conditionally extract a single element

Three of the four methods in the previous lesson (First(), Last(), and Single()) have another form that accepts a delegate parameter to make them more selective in which element they return. The provided delegate should take a parameter of type T and return a bool indicating whether or not the provided parameter meets the criteria.

NOTE: Same remark as in the previous lesson. If these methods can't find an appropriate element to return, they will throw an exception.

First(<predicate>) method

Any idea what this call to First() would return?

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

Last(<predicate>) method

How about this call to Last()?

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

Single(<predicate>) method

And this call to Single()?

List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.Single(val => val > 2.2);
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io