这篇文章将讨论如何在 C# 中找到 List 中的最后一个元素。
1.使用 Enumerable.Last
方法
要检索集合的最后一个元素,请使用 Enumerable.Last()
方法。这可在 System.Linq
命名空间。它可以按如下方式使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; var lastItem = nums.Last(); Console.WriteLine(lastItem); // 5 } } |
这 Last()
扩展方法抛出 System.InvalidOperationException
如果集合不包含任何元素。考虑使用 Enumerable.LastOrDefault()
方法,它返回集合的最后一个元素,如果集合为空,则返回默认值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; var lastItem = nums.LastOrDefault(); Console.WriteLine(lastItem); // 5 } } |
2.使用 ^
操作员
如果您使用的是 C# 8,您可以使用 ^
运算符访问列表中的最后一个元素。下面的示例显示了 this 的调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; if (nums.Count > 0) { var lastItem = nums[^1]; Console.WriteLine(lastItem); // 5 } } } |
或者,您可以使用索引运算符访问列表的最后一项。下面的代码示例展示了它的用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; if (nums.Count > 0) { var lastItem = nums[nums.Count - 1]; Console.WriteLine(lastItem); // 5 } } } |
这就是在 C# 中查找列表中的最后一个元素。