Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Adding and Removing range of items from a list in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.58k
    Comment on it

    Many times, we being the developers come across a scenario where we need to Add or Remove a range of Items in a list.

    In c# we have a function called AddRange to add a range of same data type elements in to a list that also has the same data type.

    For removing the range of elements from a list, we have RemoveRange function.

    Here is the code for the same

    class Program
        {
            static void Main(string[] args)
            {
                string[] colors = { "Black", "White", "Blue", "Green", "Orange" };
                List<string> colorList = colors.ToList();
    
                Console.WriteLine("All colors");
                foreach (string color in colorList)
                {
                    Console.WriteLine(color);
                }
    
                Console.WriteLine("\nAdd range of colors to the existing color List");
                colorList.AddRange(colorList);//Add Range takes list of same data type
                foreach (string color in colorList)
                {
                    Console.WriteLine(color);
                }
    
                Console.WriteLine("\nRemove color number 2 to 4 from color List");
                colorList.RemoveRange(1,3);//First parameter "1" is for setting the index from where the removal shall start, Second parameter"3" is the count of elements to be removed.
                foreach (string color in colorList)
                {
                    Console.WriteLine(color);
                }
    
                Console.Read();
    
            }
        }
    

    Signature of AddRange function is as below.

    public void AddRange(IEnumerable<T> collection);
    

    Signature of RemoveRange function is as below

    public void RemoveRange(int index, int count);
    

    Output of the Program will look like this

    All Colors
    Black
    White
    Blue
    Green
    Orange
    
    Add range of colors to the existing color List
    Black
    White
    Blue
    Green
    Orange
    Black
    White
    Blue
    Green
    Orange
    
    Remove color number 2 to 4 from List
    Black
    Orange
    Black
    White
    Blue
    Green
    Orange
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: