Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

LINQ: Introducing The Skip Last Operators

0.00/5 (No votes)
12 Dec 2010CPOL 20.1K  
LINQ: Introducing The Skip Last Operators
free hit countersLINQ With C# (Portuguese)

After having introduced the TakeLast operators (>)(>)(>), it makes sense to introduce their duals: the SkipLast operators.

NameDescriptionExample
SkipLast<TSource>(IEnumerable<TSource>)

Returns all but a specified number of contiguous elements from the end of a sequence.

C#
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

var lowerGrades = grades
                  .OrderBy(g => g)
                  .SkipLast(3);

Console.WriteLine("All grades except the top 
	three are:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
This code produces the following output:

All grades except the top three are:
56
59
70
82
*/
SkipLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

Returns all the elements from sequence skipping those at the end as long as the specified condition is true.

C#
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

var lowerGrades = grades
                 .OrderBy(grade => grade)
                 .SkipLastWhile(grade => 
			grade >= 80);

Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
This code produces the following output:

All grades below 80:
56
59
70
*/
SkipLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)

Returns all the elements from sequence skipping those at the end as long as the specified condition is true.

C#
int[] amounts =
    {
        5000,
        2500,
        5500,
        8000,
        6500,
        4000,
        1500,
        9000
    };

var query = amounts
            .SkipWhile((amount, index) => 
		amount > index * 1000);

foreach (int amount in query)
{
    Console.WriteLine(amount);
}

/*
 This code produces the following output:

9000
*/

You can find these (and more) operators in my CodePlex project for LINQ utilities and operators: PauloMorgado.Linq.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)