How to remove a sublist from a List in C#

2 Answers

0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
        List<int> list2 = new List<int> { 3, 4 };

        list1.RemoveAll(item => list2.Contains(item));
        
         Console.WriteLine(string.Join(", ", list1));
    }
}


/*
run:
 
1, 2, 5, 6, 7
 
*/

 



answered Aug 13, 2025 by avibootz
0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        
        // Define the start index and count of elements to remove
        int startIndex = 2; // Starting at index 2 (third element)
        int endIndex = 5;   // Ending at index 5 (sixth element)
        
        // Calculate the count of elements to remove
        int count = endIndex - startIndex + 1;

        // Remove the range
        numbers.RemoveRange(startIndex, count);

        // Print the updated list
        Console.WriteLine(string.Join(", ", numbers));
    }
}



/*
run:
 
1, 2, 7, 8, 9
 
*/

 



answered Aug 13, 2025 by avibootz

Related questions

...