C# LINQ Enumerable.Last Method in ASP.Net

Updated on 10 Apr 2012,
Published on 19 Oct 2010

The Last method of System.Linq.Enumerable class enables to get the last element from a sequence. By default it returns the last element from a sequence. Alternatively, its overloaded function returns the first occurrence of an element starting from the last index of a sequence that satisfies the specified condition. The LINQ Last method has the following two overloaded forms which accept zero or one parameter and returns the output accordingly:

1.

public static TSource Last<TSource>(this IEnumerable<TSource> source);

It takes no parameter and returns the last element of the sequence.

2.

public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

It takes one parameter as a predicate test condition that returns the last element from a sequence that satisfies the provided condition.

C# LINQ First Method Example in ASP.Net

// Example 1:
int[] numbers = { 10, 20, 30, 80, 70, 60, 50, 40 };

int number = numbers.Last();

Response.Output.Write("{0}<br />", number);

// Example 2:
number = numbers.Last(n => n > 40);

Response.Output.Write("{0}<br />", number);

// Output:
// 40
// 50

In the above C# sample code we have created two examples to illustrate the use of Last method. In the first example we have passed no parameter to the method to get the last element from the sequence by default. But in second example we have passed a Lambda expression to specify a test condition that will return the last number from the sequence that is greater than 40.

Continue to next tutorial: C# LINQ Enumerable.LastOrDefault Method in ASP.Net to learn how to get a default value from a sequence if no element is found.

0 Responses to "C# LINQ Enumerable.Last Method in ASP.Net"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers