📜  c# list get element from end - C# (1)

📅  最后修改于: 2023-12-03 15:29:45.895000             🧑  作者: Mango

C# List获取倒数第N个元素

在C#编程中,List是一种非常常用的数据结构。有时候我们需要从列表的末端开始获取元素,那么如何在C#中获取List的倒数第N个元素呢?

方式一:使用List的Count属性

我们可以利用List的Count属性来获取List的长度,然后使用List<int>.Count - N的方式来计算倒数第N个元素的索引,最后使用List的索引访问方法获取对应元素。

List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
int n = 2; // 获取倒数第2个元素
int index = list.Count - n;
int lastNElement = list[index];
Console.WriteLine(lastNElement); // 输出4
方式二:使用LINQ

除了方式一,我们还可以使用LINQ的方式获取List的倒数第N个元素。先使用Enumerable.Reverse方法将List反转,然后通过Enumerable.ElementAtOrDefault方法获取倒数第N个元素。

List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
int n = 2; // 获取倒数第2个元素
int lastNElement = list.Reverse().ElementAtOrDefault(n - 1);
Console.WriteLine(lastNElement); // 输出4

需要注意的是,使用Reverse方法会改变原List的顺序,如果需要保留原List的顺序,还需要在获取完元素后再次调用Reverse方法将List反转。

方式三:扩展方法

我们还可以自定义一个扩展方法,通过索引来获取List的倒数第N个元素。

public static class ListExtensions
{
    public static T LastNElement<T>(this List<T> list, int n)
    {
        int index = list.Count - n;
        return list[index];
    }
}

使用方式:

List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
int n = 2; // 获取倒数第2个元素
int lastNElement = list.LastNElement(n);
Console.WriteLine(lastNElement); // 输出4

以上三种方式都可以有效地获取List的倒数第N个元素。对于不同的场景,不同的方式可能会有不同的适用性,可以根据实际情况选择合适的方式。