Finding the last index of an array

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

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

11条回答
  •  星月不相逢
    2020-12-10 01:10

    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.
    

提交回复
热议问题