Get the Last Element of a List in C#

  1. Get the Last Element of a List With the List.Count Property in C
  2. 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#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp List

  • ArrayList vs List in C#
  • Check if List Is Empty in C#