C# 查找数组的最后一个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1056749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the last index of an array
提问by MAC
How do you retrieve the last element of an array in C#?
你如何在 C# 中检索数组的最后一个元素?
采纳答案by Fredrik M?rk
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
.
该数组有一个Length
属性,可以为您提供数组的长度。由于数组索引是从零开始的,最后一项将在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:
在 C# 中声明数组时,您给出的数字是数组的长度:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
回答by sharptooth
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.
如果数组为空,将得到 -1 - 您应该将其视为特殊情况。
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),则会导致异常。
回答by Cambium
say your array is called arr
说你的数组叫做 arr
do
做
arr[arr.Length - 1]
回答by Nippysaurus
The following will return NULL if the array is empty, else the last element.
如果数组为空,以下将返回 NULL,否则返回最后一个元素。
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
回答by sisve
Use Array.GetUpperBound(0). Array.Lengthcontains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.
使用Array.GetUpperBound(0)。Array.Length包含数组中的项目数,因此读取 Length -1 仅适用于数组从零开始的假设。
回答by dribnet
回答by Imad
Is this worth mentioning?
这值得一提吗?
var item = new Stack(arr).Pop();
回答by Matthew Steven Monkan
回答by picolino
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) you can use Index
type to keep array's indexes from end:
此外,从 .NET Core 3.0(和 .NET Standard 2.1)开始,您可以使用Index
type 来保持数组的索引从末尾开始:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any lenght 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