How to remove the last N elements from a list in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
   
class Program
{
    public static void RemoveLast<T>(List<T> list, int N) {
        list.RemoveRange(N + 1, list.Count - N - 1);
    }
    static void Main() {
        var list = new List<string> { "c++", "c#", "go", "c", "python", "java", "php" };
   
        int N = 3;
        
        RemoveLast(list, N);

        Console.WriteLine(string.Join(", ", list));
    }
}
   
   
   
   
/*
run:
      
c++, c#, go, c
    
*/

 



answered Jul 6, 2023 by avibootz

Related questions

1 answer 125 views
2 answers 236 views
1 answer 141 views
1 answer 86 views
1 answer 249 views
1 answer 100 views
...