Back
Close

Using C# LINQ - A Practical Overview

player_one
69.1K views
Previous: Extract a single element Next: Single element or default

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?
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
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants