Partition Operations
Partition operations divide input sequences into sections and return a single section.
These operations do not alter the order of elements. These operations utilize four methods: Skip, SkipWhile, Take, and TakeWhile.
The Skip method skips elements to the point of a specified sequence position. Review its syntax below:
public static IEnumerable<TSource> Skip<TSource>( this IEnumerable<TSource> source, int count )
Review an example of its use below:
int[] rankings = { 12, 23, 22, 33, 32, 31, 10 };
IEnumerable<int> lowerRanked = rankings.OrderByDescending(r => r).Skip(3);
Console.WriteLine("All rankings except the top 3 follow:");
foreach (int rankings in lowerRanked)
{
Console.WriteLine(rankings);
}
The SkipWhile method skips elements based on predicate function conditions until it encounters an element out of compliance with the condition. Review its syntax below:
public static IEnumerable<TSource> SkipWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
Review an example of its use below:
int[] ranking = { 12, 23, 22, 33, 32, 31, 10 };
IEnumerable<int> lowerRanked =
ranking
.OrderByDescending(ranking => ranking)
.SkipWhile(ranking => ranking => 20);
Console.WriteLine("All rankings below 20:");
foreach (int ranking in lowerRanked)
{
Console.WriteLine(ranking);
}
The Take method takes elements to the point of a specified sequence position. Review its syntax below:
public static IEnumerable<TSource> Take<TSource>( this IEnumerable<TSource> source, int count )
Review an example of its use below:
int[] rankings = {12, 23, 22, 33, 32, 31, 10};
IEnumerable<int> topThreeRankings =
rankings.OrderByDescending(ranking => ranking).Take(3);
Console.WriteLine("The top three ranks follow:");
foreach (int ranking in topThreeRankings)
{
Console.WriteLine(ranking);
}
The TakeWhile method takes elements based on predicate function conditions until it encounters an element out of compliance with the condition. Review its syntax below:
public static IEnumerable<TSource> TakeWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
Review an example of its use below:
string[] candies = { "gum", "chews", "chocolate", "gummi", "lollipop", "sourpower" };
IEnumerable<string> query =
candies.TakeWhile(candy => String.Compare("gummi", candy, true) != 0);
foreach (string candy in query)
{
Console.WriteLine(candy);
}