[英]Finding the last index of an array
如何检索 C# 中数组的最后一个元素?
LINQ 提供Last() :
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
当您不想不必要地创建变量时,这很方便。
string lastName = "Abraham Lincoln".Split().Last();
该数组有一个Length
属性,可以为您提供数组的长度。 由于数组索引是从零开始的,最后一项将在Length - 1
。
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
在 C# 中声明数组时,您给出的数字是数组的长度:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
使用 C# 8 :
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
使用Array.GetUpperBound(0) 。 Array.Length包含数组中的项数,因此读取 Length -1 仅适用于数组从零开始的假设。
在 C# 8.0 中,您可以使用所谓的“帽子”(^) 运算符! 当您想在一行中做某事时,这很有用!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
而不是旧的方式:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
它并没有节省多少空间,但看起来更清晰(也许我认为这是因为我来自 python?)。 这也比调用.Last()
或.Reverse()
的方法要好得多在 MSDN 上阅读更多内容
编辑:您可以将此功能添加到您的班级中,如下所示:
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!")
}
}
}
}
Index.IsFromEnd
会告诉您是否有人在使用“帽子”(^) 运算符
计算最后一项的索引:
int index = array.Length - 1;
如果数组为空,将得到 -1 - 您应该将其视为特殊情况。
要访问最后一个索引:
array[array.Length - 1] = ...
要么
... = array[array.Length - 1]
如果数组实际上为空(长度为 0),则会导致异常。
如果数组为空,以下将返回 NULL,否则返回最后一个元素。
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
说你的数组叫做 arr
做
arr[arr.Length - 1]
此外,从 .NET Core 3.0(和 .NET Standard 2.1)(C# 8)开始,您可以使用Index
类型来保持数组的索引不结束:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
您可以使用此索引获取任意长度数组中的最后一个数组值。 例如:
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
有关更多信息,请查看文档
这值得一提吗?
var item = new Stack(arr).Pop();
数组从索引 0 开始,到 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();
}
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;
}
}
这是最简单的,适用于所有版本。
int[] array = { 1, 3, 5 };
int last = array[array.Length - 1];
Console.WriteLine(last);
// 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.