In LINQ, the Last() method is useful to return the last element from the list/collection, and this LINQ Last() method will throw an exception if the list/collection returns no elements.
Syntax of LINQ Last() Method
Following is the syntax of using the LINQ Last() method to get the last element from the list using the 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 the 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 the above code, we get the last element from the “objList” list using the LINQ Last() method.
Result of LINQ Last() in Method Syntax
Following is the result of LINQ Last() in the method syntax example.
Element from the List: 5
Example of LINQ Last() in Query Syntax
The following is the 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
Result 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 the last element from the list in c#, vb.net.