
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to insert an item into a C# list by using an index?
Firstly, set a list −
List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459);
Now, to add an item at index 5, let say; for that, use the Insert() method −
list.Insert(5, 999);
Let us see the complete example −
Example
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("
Count: {0}", list.Count); // inserting element at index 5 list.Insert(5, 999); Console.Write("
List after inserting a new element: "); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine("
Count: {0}", list.Count); } } }
- Related Articles
- How to remove an item from a C# list by using an index?
- Golang Program to insert an item into the array without using library function
- How to insert an item in a list at a given position in C#?
- How to insert an element into DOM using jQuery?
- How to insert an image in a Tkinter canvas item?
- How do I insert an item between two items in a list in Java?
- How to find the index of an item given a list containing it in Python?
- Python program to insert an element into sorted list
- How to insert an item in ArrayList in C#?
- How to find the index of an item in a C# list in a single step?
- How to append an item into a JavaScript array?
- Insert an element into Collection at specified index in C#
- How to insert an item to an array that is inside an object in MongoDB?
- How to remove an element from a list by index in Python?
- How to add an item to a list in Kotlin?

Advertisements