Using C# LINQ - A Practical Overview
player_one
1696K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Combined Exercise #1
As we have already seen in some of the examples, LINQ methods can build on each other. Since many LINQ methods return an IEnumerable<T>
, subsequent LINQ methods can be called on the results. For example:
IEnumerable<string> values = new List<string> { "fe", "fi", "fo", "fum" };
// Will return 12
int result = values
.Select(word => $"{word}-{word}") // { "fe-fe", "fi-fi", ... }
.Skip(2)
.Select(phrase => phrase.Length)
.Sum();
In this exercise, combine LINQ method calls together to determine if the second sequence passed into the TestForSquares()
method contains the squares of the elements in the first sequence. It should return true
if the two sequences have the same number of elements and each element in squares
is equal to the square of the corresponding element in numbers
.
Combined Exercise 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Collections.Generic;
using System.Linq;
namespace AllTogether1
{
public class FullExercise1
{
// The following method should return true if each element in the squares sequence
// is equal to the square of the corresponding element in the numbers sequence.
// Try to write the entire method using only LINQ method calls, and without writing
// any loops.
public static bool TestForSquares(IEnumerable<int> numbers, IEnumerable<int> squares)
{
return numbers
// .???().???() ... .???()
;
}
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content