Back
Close

Using C# LINQ - A Practical Overview

player_one
69.3K views
Previous: Single element or default Next: Skip and Take

Exercise - Extract a single element

Using what you have learned about First(), Last(), ElementAt(), and Single() (and their variations) modify the methods in this exercise to extract the desired element from the provided sequence of strings.

For reference, here are some examples of LINQ methods that return a single element from the sequence:

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

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


List<double> doubles = new List<double> { 2.0, 2.1, 2.2, 2.3 };
double whatsThis = doubles.ElementAtOrDefault(4);
Extract a Single Value Exercise
using System.Collections.Generic;
using System.Linq;
namespace SingleValue1
{
public static class SingleValue1
{
// Return the first word with just one letter in it, out of a sequence of words.
// There will always be at least one.
public static string GetFirstSingleLetterWord(IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
// Return the last word that contains the substring "her" in it.
// There will always be at least one.
public static string GetLastWordWithHerInIt(IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
// Return the fifth word in the sequence, if there is one. If there are
// fewer than 5 words, then return null.
public static string GetFifthWordIfItExists(IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
// Return the last word in the sequence. If there are no words in
// the sequence, return null.
public static string GetLastWordIfAny(IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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