- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert more than one element at once in a C# List
Use the InsertRange() method to insert a list in between the existing lists in C#. Through this, you can easily add more than one element to the existing list.
Let us first set a list −
List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50);
Now, let us set an array. The elements of this array are what we will add to the above list −
int[] arr2 = new int[4]; arr2[0] = 60; arr2[1] = 70; arr2[2] = 80; arr2[3] = 90;
We will add the above elements to the list −
arr1.InsertRange(5, arr2);
Here is the complete code −
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); Console.WriteLine("Initial List ..."); foreach (int i in arr1) { Console.WriteLine(i); } int[] arr2 = new int[4]; arr2[0] = 60; arr2[1] = 70; arr2[2] = 80; arr2[3] = 90; arr1.InsertRange(5, arr2); Console.WriteLine("After adding elements ..."); foreach (int i in arr1) { Console.WriteLine(i); } } }
Output
Initial List ... 10 20 30 40 50 After adding elements ... 10 20 30 40 50 60 70 80 90
Advertisements