C# List.InsertRange() strategy: Here, we will find out about the InsertRange() technique for List with example.
C# List.InsertRange() Method
List.InsertRange() strategy is utilized to embed an assortment of components of the same kind at the indicated list in the rundown.
Syntax:
void List<T>.InsertRange(int index, IEnumerable<T> collection);
Parameter: It acknowledges two parameters 1) list – where you need to embed the components and 2) assortment – an assortment of the components of type T.
Return value: It returns nothing – it’s arrival type is void.
Example:
int list declaration:
List<int> a = new List<int>();
adding elements:
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//inserting elements (array) at specified indexes
int[] arr = { 100, 200, 300 };
a.InsertRange(3, arr);
Output:
10 20 30 100 200 300 40 50
C# Example to embed an assortment of components at the determined file in the rundown utilizing List.InsertRange() Method:
using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void printList(List<int> lst)
{
//printing elements
foreach (int item in lst)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//integer list
List<int> a = new List<int>();
//adding elements
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//print the list
Console.WriteLine("list elements...");
printList(a);
//inserting elements (array) at specified indexes
int[] arr = { 100, 200, 300 };
a.InsertRange(3, arr);
//list after inserting elements
Console.WriteLine("list elements after inserting elements...");
printList(a);
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output:
list elements...
10 20 30 40 50
list elements after inserting elements...
10 20 30 100 200 300 40 50