C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part A: This Take call returns the first 2 elements in the List. This could display the 2 oldest, first elements.
Part B: The second Take call is chained after a Reverse<string> call. It operates on the result of Reverse.
ReversePart C: The final Take call uses the top 1000 elements, which is nonsense as there are not 1000 elements in the List.
ListC# program that uses Take
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");
list.Add("programmer");
// Part A: get first 2 elements.
var first = list.Take(2);
foreach (string s in first)
{
Console.WriteLine(s);
}
Console.WriteLine();
// Part B: get last 2 elements reversed.
var last = list.Reverse<string>().Take(2);
foreach (string s in last)
{
Console.WriteLine(s);
}
Console.WriteLine();
// Part C: get first 1000 elements.
var all = list.Take(1000);
foreach (string s in all)
{
Console.WriteLine(s);
}
Console.WriteLine();
}
}
Output
cat
dog
programmer
dog
cat
dog
programmer
Info: TakeWhile operates from the beginning of an IEnumerable collection. It can be called on the result of another method like Skip.
PredicatePart 1: An integer array of 5 elements is declared. The first 3 numbers in it are odd, while the last 2 are even.
Odd, EvenPart 2: The TakeWhile extension method is invoked. It returns the first 3 odd numbers, but not the even numbers at the end.
LambdaModuloC# program that uses TakeWhile method
using System;
using System.Linq;
class Program
{
static void Main()
{
// Part 1: create array with 5 numbers.
int[] values = { 1, 3, 5, 8, 10 };
// Part 2: take all non-even (odd) numbers.
var result = values.TakeWhile(item => item % 2 != 0);
foreach (int value in result)
{
Console.WriteLine(value);
}
}
}
Output
1
3
5
Info: We call SkipWhile to skip some lower-value elements, and then call TakeWhile to take some until a limit is reached.
C# program that uses SkipWhile and TakeWhile
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] values = { 10, 20, 30, 40, 50, 60 };
// Use SkipWhile and TakeWhile together.
var result = values.SkipWhile(v => v < 30).TakeWhile(v => v < 50);
foreach (var value in result)
{
Console.WriteLine("RESULT: {0}", value);
}
}
}
Output
RESULT: 30
RESULT: 40