Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to insert an item into a C# list by using an index?
The Insert() method in C# allows you to add an item to a List<T> at a specific index position. This method shifts existing elements to make room for the new item, automatically increasing the list's size.
Syntax
Following is the syntax for the Insert() method −
list.Insert(index, item);
Parameters
-
index − The zero-based index at which the item should be inserted.
-
item − The object to insert into the list.
How It Works
When you use Insert(), the method shifts all elements at and after the specified index one position to the right, then places the new item at the specified index.
Example
Let us see how to insert an item at a specific index −
using System;
using System.Collections.Generic;
namespace Demo {
public class Program {
public static void Main(string[] args) {
List<int> list = new List<int>();
list.Add(456);
list.Add(321);
list.Add(123);
list.Add(877);
list.Add(588);
list.Add(459);
Console.Write("List: ");
foreach (int i in list) {
Console.Write(i + " ");
}
Console.WriteLine("\nCount: {0}", list.Count);
// inserting element at index 5
list.Insert(5, 999);
Console.Write("\nList after inserting a new element: ");
foreach (int i in list) {
Console.Write(i + " ");
}
Console.WriteLine("\nCount: {0}", list.Count);
}
}
}
The output of the above code is −
List: 456 321 123 877 588 459 Count: 6 List after inserting a new element: 456 321 123 877 588 999 459 Count: 7
Using Insert at Different Positions
Example
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<string> fruits = new List<string> { "Apple", "Orange", "Grapes" };
Console.WriteLine("Original list:");
foreach (string fruit in fruits) {
Console.Write(fruit + " ");
}
// Insert at beginning (index 0)
fruits.Insert(0, "Mango");
// Insert at middle (index 2)
fruits.Insert(2, "Banana");
// Insert at end (index equals Count)
fruits.Insert(fruits.Count, "Pineapple");
Console.WriteLine("
\nAfter insertions:");
foreach (string fruit in fruits) {
Console.Write(fruit + " ");
}
}
}
The output of the above code is −
Original list: Apple Orange Grapes After insertions: Mango Apple Banana Orange Grapes Pineapple
Key Rules
-
The index must be valid − between 0 and the current
Countof the list (inclusive). -
Using
Insert(list.Count, item)is equivalent toAdd(item). -
If the index is greater than
Count, anArgumentOutOfRangeExceptionis thrown. -
The
Insert()operation has O(n) time complexity due to element shifting.
Conclusion
The Insert() method provides precise control over where new items are placed in a List<T>. It automatically shifts existing elements and increases the list size, making it ideal for maintaining ordered collections where position matters.
