查找数组的最后一个索引

MAC*_*MAC 38 c# arrays

你如何在C#中检索数组的最后一个元素?

dri*_*net 108

LINQ提供Last():

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

当您不想不必要地创建变量时,这很方便.

string lastName = "Abraham Lincoln".Split().Last();
Run Code Online (Sandbox Code Playgroud)

  • 这应该是最好的答案 (2认同)
  • 最后一个很好,但是只获取最后一个项目是非常具体的。C# 是否有类似 slice 的东西,可以使用 `slice(-2)` 来获取最后 2 个,或者使用 `slice(0,-2)` 来从头开始获取除最后 2 个之外的项目?然后像 Last 这样的函数就不需要了,因为我们可以像我在其他语言中所做的那样只执行 `slice(-1)` 。 (2认同)
  • @HMR 是的,请参阅:https://www.infoq.com/articles/cs8-ranges-and-recursive-patterns (2认同)

Mat*_*kan 53

使用 C# 8

int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
Run Code Online (Sandbox Code Playgroud)

  • 需要 C# 8 和 .Net Framework 4.8 或 .Net Core 3。 https://github.com/ashmind/SharpLab/issues/390 (5认同)

Fre*_*örk 50

该数组有一个Length属性,可以为您提供数组的长度.由于数组索引从零开始,最后一项将是Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
Run Code Online (Sandbox Code Playgroud)

在C#中声明数组时,您给出的数字是数组的长度:

string[] items = new string[5]; // five items, index ranging from 0 to 4.
Run Code Online (Sandbox Code Playgroud)

  • 当数组为零项时,这会失败,在这种情况下`(items.Length - 1)== -1` (7认同)
  • 在 C# 8 中,有一个新的索引运算符:`char[] arr = {'c', 'b', 'a'}; int a_last = arr[^1]; int b_second_last = arr[^2];` (6认同)

sis*_*sve 7

使用Array.GetUpperBound(0).Array.Length包含数组中的项数,因此读取长度-1仅适用于假设数组基于零的情况.

  • 并非C#中的所有数组都是基于零的吗? (3认同)

sha*_*oth 5

计算最后一项的索引:

int index = array.Length - 1;
Run Code Online (Sandbox Code Playgroud)

如果数组为空,则会得到 -1 - 你应该将其视为特殊情况。

要访问最后一个索引:

array[array.Length - 1] = ...
Run Code Online (Sandbox Code Playgroud)

或者

... = array[array.Length - 1]
Run Code Online (Sandbox Code Playgroud)

如果数组实际上为空(长度为 0),则会引发异常。


rzk*_*zk3 5

在 C# 8.0 中,您可以使用所谓的“帽子”(^) 运算符!当您想在一行中做某事时,这很有用!

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

而不是旧的方式:

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

它并没有节省多少空间,但看起来更清晰(也许我认为这是因为我来自 python?)。这也比调用MSDN 之类的方法.Last()阅读更多内容要好得多.Reverse()

编辑:您可以像这样将此功能添加到您的课程中:

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!")
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Index.IsFromEnd会告诉你,如果有人使用“帽子”(^)运算符