LINQ Last() Method

  Total Views : 191
  Comments : 0
 
  Keywords : Linq last() method in c# / vb.net with example, How to use linq last() method to get element from the list / collection in c# / vb.net with example, Get last element from list in Linq last()

Here we will learn LINQ Last() method in c#, vb.net with example and how to use LINQ Last() in method syntax and query syntax to get last from the list or collection in c#, vb.net with example.

LINQ Last() Method

In LINQ Last() method is used to return last element from the list / collection and this LINQ Last() method will throw an exception in case if the list / collection returns no elements.

Syntax of LINQ Last() Method

Following is the syntax of using LINQ Last() method to get last element from the list using LINQ Last() method.

 

C# Code

 

int result = objList.Last();

VB.NET Code

 

Dim result As Integer = objList.Last()

If you observe above syntax we are trying to get last element from the “objList” list using LINQ Last() method.

Example of LINQ Last in Method Syntax

Following is the syntax of using LINQ Last() operator in method syntax to get last element from the list.

 

C# Code

 

using System;

using System.Linq;

 

namespace LINQExamples

{

class Program

{

static void Main(string[] args)

{

int[] objList = { 1, 2, 3, 4, 5 };

int result = objList.Last();

Console.WriteLine("Element from the List: {0}", result);

Console.ReadLine();

}

}

}

VB.NET Code

 

Module Module1

Sub Main()

Dim objList As Integer() = {1, 2, 3, 4, 5}

Dim result As Integer = objList.Last()

Console.WriteLine("Element from the List: {0}", result)

Console.ReadLine()

End Sub

End Module

If you observe above code we are getting last element from “objList” list by using LINQ Last() method.

Output of LINQ Last() in Method Syntax

Following is the result of LINQ Last() in method syntax example.

 

Element from the List: 5

Example of LINQ Last() in Query Syntax

Following is the example of LINQ Last() operator in query syntax to get last element from the list.

 

C# Code

 

using System;

using System.Linq;

 

namespace LINQExamples

{

class Program

{

static void Main(string[] args)

{

int[] objList = { 1, 2, 3, 4, 5 };

int result = (from l in objList select l).Last();

Console.WriteLine("Element from the List: {0}", result);

Console.ReadLine();

}

}

}

VB.NET Code

 

Module Module1

Sub Main()

Dim objList As Integer() = {1, 2, 3, 4, 5}

Dim result As Integer = (From l In objList).Last()

Console.WriteLine("Element from the List: {0}", result)

Console.ReadLine()

End Sub

End Module

Output of LINQ Last() in Query Syntax Example

Following is the result of LINQ Last() operator in query syntax example.

 

Element from the List: 5

This is how we can use LINQ Last() operator in method syntax and query syntax to get last element from the list in c#, vb.net.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User