List.AddRange() method with example in C#

C# List.AddRange() strategy: Here, we will find out about the AddRange() technique for List with example.

C# List.AddRange() Method

List.AddRange() strategy is utilized to include the items/components of a predefined assortment toward the finish of the rundown.

Syntax:

    void List<T>.AddAddRange(IEnumerable<T> collection);

Parameter: It acknowledges an assortment of components (like varieties) of T type to include the List.

Return value: It returns nothing – it’s arrival type is void

Example:

    int list declaration:
    List<int> a = new List<int>();
    
    int array to be added to the list:
    int[] int_arr = { 100, 200, 300, 400 };

    adding elements:
    a.AddRange(int_arr);

    Output:
    100 200 300 400

C# Example to add things to the rundown utilizing List.AddRange() Method:

using System;
using System.Text;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //integer list
            List<int> a = new List<int>();
            //int array to add in the list
            int[] int_arr = { 100, 200, 300, 400 };

            //adding elements
            a.Add(10);
            a.Add(20);
            //adding range 
            a.AddRange(int_arr);

            //printing elements
            Console.WriteLine("list elements are...");
            foreach(int item in a)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            //string list
            List<string> b = new List<string>();
            //string array to add in the list
            string[] str_arr = { "Abhi", "Radib", "Prem" };
            //adding elements
            b.Add("Manju");
            b.Add("Amit");
            //adding range
            b.AddRange(str_arr);

            //printing elements
            Console.WriteLine("list elements are...");
            foreach (string item in b)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

list elements are...
10 20 100 200 300 400
list elements are...
Manju Amit Abhi Radib Prem

Leave a Comment

error: Alert: Content is protected!!