How to Get the Last Element of a List in C#
-
Get the Last Element of a List With the
List.Count
Property inC#
-
Get the Last Element of a List With the LINQ Method in
C#
This tutorial will discuss the methods to get the last element of a list in C#.
Get the Last Element of a List With the List.Count
Property in C#
The List.Count
property gives the number of elements inside the list in C#. We can get the last index of the list by subtracting 1
from the List.Count
value. We can then find the last element of the list by using this index.
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[slist.Count - 1];
Console.WriteLine(last);
}
}
}
Output:
value3
In the above code, we stored the last element of the list of strings slist
in the string variable last
with the slist.Count
property in C#. We calculated the last index of the slist
with slist.Count - 1
and stored the element at that index in the last
string.
Get the Last Element of a List With the LINQ Method in C#
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
In the above code, we stored the last element of the list of strings slist
in the string variable last
with the slist.Last()
property in C#.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn