从列表中删除最后x个元素

时间:2013-08-10 05:47:04

标签: c# list

假设我有List<Car> Cars有n项,我想删除最后两项。我找到的最好方法是:

Cars.RemoveRange(Cars.Count-2, 2);

有更好的方法吗?我在搜索这样的东西:

Cars.RemoveFrom(Cars.Count-2); //pseudocode

2 个答案:

答案 0 :(得分:6)

不,没有...但如果你想要,你可以把它放在扩展方法中。

static class ListEx
{
    public static void RemoveFrom<T>(this List<T> lst, int from)
    {
        lst.RemoveRange(from, lst.Count - from);
    }
}

答案 1 :(得分:0)

现在我们可以选择

void List<T>.RemoveRange(int index, int count);

有关核心信息,请参见Microsoft Docs List.RemoveRange(Int32, Int32) Method

Microsoft Docs List.RemoveRange(Int32, Int32) Method for Framework 4.8

适用于

.NET Core 3.1 3.0 2.2 2.1 2.0 1.1 1.0

.NET Framework 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0

.NET标准 2.1 2.0 1.6 1.4 1.3 1.2 1.1 1.0

相关问题