Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last x elements from the list

Tags:

c#

list

Lets say I have a List<Car> Cars that have n items and I want to delete the last two. The best way that I found is:

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

Is there better way? I searching something like this:

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

like image 357
biox Avatar asked Aug 10 '13 05:08

biox


2 Answers

No, there isn't... But if you want you can put it in an extension method.

static class ListEx
{
    public static void RemoveFrom<T>(this List<T> lst, int from)
    {
        lst.RemoveRange(from, lst.Count - from);
    }
}
like image 56
xanatos Avatar answered Oct 05 '22 13:10

xanatos


Now we have the option

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

See Microsoft Docs List.RemoveRange(Int32, Int32) Method for Core

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

Applies To

.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 Standard 2.1 2.0 1.6 1.4 1.3 1.2 1.1 1.0

like image 38
jAntoni Avatar answered Oct 05 '22 15:10

jAntoni