Using C# LINQ - A Practical Overview
player_one
1695.4K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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.???();
}
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content