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 add items to a list in C#?
In C#, you can add items to a List<T> using several methods. The most common approach is using the Add() method to add single items, but there are also methods to add multiple items at once.
Syntax
Following is the syntax for creating a list and adding items −
var listName = new List<datatype>(); listName.Add(item);
To add multiple items at once −
listName.AddRange(collection);
Using Add() Method
The Add() method adds a single item to the end of the list −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var teams = new List<string>();
teams.Add("US");
teams.Add("Canada");
teams.Add("India");
teams.Add("Australia");
Console.WriteLine("Elements...");
foreach (var country in teams) {
Console.WriteLine(country);
}
}
}
The output of the above code is −
Elements... US Canada India Australia
Using AddRange() Method
The AddRange() method allows you to add multiple items from another collection in a single operation −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var teams = new List<string>();
var asianCountries = new string[] { "India", "China", "Japan" };
var europeanCountries = new List<string> { "Germany", "France", "UK" };
teams.AddRange(asianCountries);
teams.AddRange(europeanCountries);
Console.WriteLine("All countries:");
foreach (var country in teams) {
Console.WriteLine(country);
}
}
}
The output of the above code is −
All countries: India China Japan Germany France UK
Using Insert() Method
The Insert() method allows you to add an item at a specific position in the list −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
var numbers = new List<int> { 1, 3, 5 };
Console.WriteLine("Original list:");
foreach (var num in numbers) {
Console.Write(num + " ");
}
numbers.Insert(1, 2);
numbers.Insert(3, 4);
Console.WriteLine("\nAfter inserting at specific positions:");
foreach (var num in numbers) {
Console.Write(num + " ");
}
}
}
The output of the above code is −
Original list: 1 3 5 After inserting at specific positions: 1 2 3 4 5
Comparison of Methods
| Method | Purpose | Performance |
|---|---|---|
Add() |
Adds single item at end | O(1) - fastest |
AddRange() |
Adds multiple items at end | O(n) - efficient for bulk operations |
Insert() |
Adds item at specific position | O(n) - slower due to shifting elements |
Conclusion
C# provides multiple methods to add items to a list: Add() for single items, AddRange() for multiple items, and Insert() for adding at specific positions. Choose the appropriate method based on your specific needs and performance requirements.
