MOCKSTACKS
EN
Questions And Answers

More Tutorials




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

Using Reverse() 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

Conclusion

In this page (written and validated by ) you learned about Get the Last Element of a List in C# . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.