Click here to Skip to main content
15,887,371 members
Articles / Programming Languages / C# 4.0

LINQ: Introducing The Skip Last Operators

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Dec 2010CPOL 19.7K   3   1
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.

This article was originally posted at http://feeds.paulomorgado.net/paulomorgado/blogs/en

License

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


Written By
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
Generallike it have 5 Pin
Pranay Rana18-Dec-10 10:12
professionalPranay Rana18-Dec-10 10:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.