Finding the last index of an array

C#Arrays

C# Problem Overview


How do you retrieve the last element of an array in C#?

C# Solutions


Solution 1 - C#

LINQ provides Last():

csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();              
5

This is handy when you don't want to make a variable unnecessarily.

string lastName = "Abraham Lincoln".Split().Last();

Solution 2 - C#

The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;

When declaring an array in C#, the number you give is the length of the array:

string[] items = new string[5]; // five items, index ranging from 0 to 4.

Solution 3 - C#

With C# 8:

int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5

Solution 4 - C#

New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!

var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!

instead of the old way:

var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!

It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN

Edit: You can add this functionality to your class like so:

public class MyClass
{
  public object this[Index indx]
  {
    get
    {
      // Do indexing here, this is just an example of the .IsFromEnd property
      if (indx.IsFromEnd)
      {
        Console.WriteLine("Negative Index!")
      }
      else
      {
        Console.WriteLine("Positive Index!")
      }
    }
  }
}

The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator

Solution 5 - C#

Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.

Solution 6 - C#

To compute the index of the last item:

int index = array.Length - 1;

Will get you -1 if the array is empty - you should treat it as a special case.

To access the last index:

array[array.Length - 1] = ...

or

... = array[array.Length - 1]

will cause an exception if the array is actually empty (Length is 0).

Solution 7 - C#

The following will return NULL if the array is empty, else the last element.

var item = (arr.Length == 0) ? null : arr[arr.Length - 1]

Solution 8 - C#

Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:

var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];

You can use this index to get last array value in any length of array. For example:

var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5

For more information check documentation

Solution 9 - C#

say your array is called arr

do

arr[arr.Length - 1]

Solution 10 - C#

Is this worth mentioning?

var item = new Stack(arr).Pop();

Solution 11 - C#

Array starts from index 0 and ends at n-1.

static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int length = arr.Length - 1;   // starts from 0 to n-1

    Console.WriteLine(length);     // this will give the last index.
    Console.Read();
}

Solution 12 - C#

  static void Main(string[] args)
    {

        int size = 6;
        int[] arr = new int[6] { 1, 2, 3, 4, 5, 6 };
        for (int i = 0; i < size; i++)
        {

            Console.WriteLine("The last element is {0}", GetLastArrayIndex(arr));
            Console.ReadLine();
        }

    }

    //Get Last Index
    static int GetLastArrayIndex(int[] arr)
    {
        try
        {
            int lastNum;
            lastNum = arr.Length - 1;
            return lastNum;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMACView Question on Stackoverflow
Solution 1 - C#dribnetView Answer on Stackoverflow
Solution 2 - C#Fredrik MörkView Answer on Stackoverflow
Solution 3 - C#Matthew Steven MonkanView Answer on Stackoverflow
Solution 4 - C#rzk3View Answer on Stackoverflow
Solution 5 - C#sisveView Answer on Stackoverflow
Solution 6 - C#sharptoothView Answer on Stackoverflow
Solution 7 - C#NippysaurusView Answer on Stackoverflow
Solution 8 - C#picolinoView Answer on Stackoverflow
Solution 9 - C#CambiumView Answer on Stackoverflow
Solution 10 - C#ImadView Answer on Stackoverflow
Solution 11 - C#Minhajuddin KhajaView Answer on Stackoverflow
Solution 12 - C#Johnwendy EzealaView Answer on Stackoverflow