Finding the last index of an array

后端 未结 11 2173
不思量自难忘°
不思量自难忘° 2020-12-10 00:43

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

相关标签:
11条回答
  • 2020-12-10 00:48

    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();
    
    0 讨论(0)
  • 2020-12-10 00:50

    With C# 8:

    int[] array = { 1, 3, 5 };
    var lastItem = array[^1]; // 5
    
    0 讨论(0)
  • 2020-12-10 01:00

    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).

    0 讨论(0)
  • 2020-12-10 01:00

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

    var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
    
    0 讨论(0)
  • 2020-12-10 01:01

    say your array is called arr

    do

    arr[arr.Length - 1]
    
    0 讨论(0)
  • 2020-12-10 01:03

    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.

    0 讨论(0)
提交回复
热议问题