Get the Last Element of a List in C#
There are many different methods to get last element in a list in C#:1) Using List.Count property
2) Using LINQ last() Method
3) Using Reverse() Method
1) Using List.Count property
The concept here is to count elements of a list and get the element of [count - 1].using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list[list.Count()-1]);
}
}
Output
5
2) Using LINQ last() Method
The LINQ is used to perform query operations on data structures in C#. The Last() function inside the LINQ gets the last element of a data structure. We can use the Last() function to get the last element of our list.using System;
using System.Collections.Generic;
using System.Linq;
namespace last_element_of_list
{
class Program
{
static void Main(string[] args)
{
List<string> slist = new List<string> { "value1", "value2", "value3" };
string last = slist.Last();
Console.WriteLine(last);
}
}
}
Output
value3
3) Using Reverse() Method
UsingReverse()
method you can get another list with a reverse order, to get last element of original string you can get first element of reversed list using index 0.using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
List<int> reverse = Enumerable.Reverse(list).ToList();
Console.WriteLine(reverse[0]);
}
}
Output
5