Home » C#.Net

List<T>.AddRange() method with example in C#

C# List<T>.AddRange() method: Here, we are going to learn about the AddRange() method of List with example.
Submitted by IncludeHelp, on March 14, 2019

C# List<T>.AddRange() Method

List<T>.AddRange() method is used to add the objects/elements of a specified collection at the end of the list.

Syntax:

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

Parameter: It accepts a collection of elements (like, arrays) of T type to add in the List.

Return value: It returns nothing – it's return 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 items to the list using List<T>.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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.