Using C# LINQ - A Practical Overview
player_one
1694.8K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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);
What is the value of the whatsThis variable?
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);
What is the value of the whatsThis variable?
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);
What is the value of the whatsThis variable?
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content