- 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
How to insert an item in a list at a given position in C#?
To insert an item in an already created List, use the Insert() method.
Firstly, set elements −
List <int> list = new List<int>(); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909);
Now, let’s say you need to insert an item at 4th position. For that, use the Insert() method −
// inserting element at 4th position list.Insert(3, 567);
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(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909); Console.WriteLine("Count: {0}", list.Count); Console.Write("List: "); foreach(int i in list) { Console.Write(i + " "); } // inserting element at 4th position list.Insert(3, 567); Console.Write("
List after inserting a new element: "); foreach(int i in list) { Console.Write(i + " "); } Console.WriteLine("
Count: {0}", list.Count); } } }
Advertisements