- 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 an element at second position in a C# List
Here is our list −
List<string> val = new List<string> (); // list of strings val.Add("water"); val.Add("food"); val.Add("air");
Use the Insert() method to insert an element in the list. With that, also set where you want to add it. We have set the new text at position 1st −
val.Insert(1, "shelter");
The following is the complete code −
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { List<string> val = new List<string> (); // list of strings val.Add("water"); val.Add("food"); val.Add("air"); Console.WriteLine("Initial list:"); // Initial List foreach (string res in val) { Console.WriteLine(res); } // inserting an element at second position val.Insert(1, "shelter"); Console.WriteLine("New list after inserting an element:"); foreach (string res in val) { Console.WriteLine(res); } } }
Output
Initial list: water food air New list after inserting an element: water shelter food air
Advertisements