Search This Blog

Thursday, April 7, 2011

Take Last Operators

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

var topThreeGrades = grades
.OrderBy(grade => grade)
.TakeLast(3);

Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
Console.WriteLine(grade);
}
/*
This code produces the following output:

The top three grades are:
98
92
85
*/
----------------------------------------------------
string[] fruits =
{
"apple",
"passionfruit",
"banana",
"mango",
"orange",
"blueberry",
"grape",
"strawberry"
};

var query = fruits
.TakeLastWhile(fruit =>
string.Compare("orange",
fruit, true) != 0);

foreach (string fruit in query)
{
Console.WriteLine(fruit);
}

/*
This code produces the following output:

blueberry
grape
strawberry
*/
---------------------------------------

string[] fruits =
{
"apple",
"passionfruit",
"banana",
"mango",
"orange",
"blueberry",
"grape",
"strawberry"
};

var query = fruits
.TakeLastWhile((fruit, index) =>
fruit.Length >= index);

foreach (string fruit in query)
{
Console.WriteLine(fruit);
}

/*
This code produces the following output:

strawberry
*/

No comments:

Post a Comment