List in C# is a Generic collection class that allows you to access its items by index. List<T> represents a list of strongly typed objects, that means you can explicitly define the type of object the list can hold.
In C# List has properties similar to an array. however, List automatically expands as the number of elements increases, where as size of an array remains fixed.
Create a List in C#
You need to specify a type parameter while creating a List<T>. The following example shows that.
1 2 3 4 5 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Creating a list of int objects var lstNumbers = new List<int>(); |
In above example.
- List<string> lstCountry = new List<string>(); creates a list that holds only string values.
- var lstNumbers = new List<int>(); creates a list that holds only int values.
Add item to a List in C#
You can use Add() method to add new item to a List<T> of same type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry list object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Creating a list of int objects var lstNumbers= new List<int>(); //Adding items to lstNumbers list object lstNumbers.Add(11); lstNumbers.Add(12); lstNumbers.Add(13); lstNumbers.Add(14); |
In above, we are adding string items to list lstCountry and int values to list lstNumbers using Add() method. It gives compile error if you add different types of item in to the list.
Create a List using object initializer syntax
You can also use the object initializer syntax to create a strongly typed list object and add elements to it in a single statement. In below example, we are creating list using object initializer syntax.
1 2 3 4 5 6 7 8 9 10 |
//Declaring a collection object and adding items using collection-initializer syntax List<string> lstCountry = new List<string>() { "India", "United States", "United Kingdom", "Spain" }; //Using var keyword var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; |
Add list of Items in to another List in C#
You can use the AddRange(IEnumerable<T> collection) method to add list of items or an array of items in to another List<T>, lets have a look at below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Adding another list of items using AddRange method lstCountry.AddRange(new List<string>() { "Poland", "Greece", "Germany" }); //Adding an array of item to the list lstCountry.AddRange(new string[] { "Italy", "Brazil", "Peru", "Canada" }); |
Here in above,
- lstCountry.AddRange(new List<string>() { "Poland", "Greece", "Germany" }); adds a new list of string items to lstCountry.
- lstCountry.AddRange(new string[] { "Italy", "Brazil", "Peru", "Canada" }); adds an array of string items to lstCountry.
Remove an item from a List in C#
We have various methods available to remove an item from a List<T>
- bool Remove(T item) : This method removes the first occurrence of the specified element.
- void RemoveAt(int index) : This method removes an element from the specified index.
- void RemoveRange(int index, int count) : This method removes a range of elements from the List, here index value is the starting point and count is the number of items to be removed.
You can use the Remove() method to remove the first occurrence of the specified element from the List and use RemoveAt() method to remove an element from the specified index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Remove first occurrence of item - it will remove "United States" from the list lstCountry.Remove("United States"); //Or //Remove item at 1st index, index starts from 0 lstCountry.RemoveAt(1); |
In above, this lstCountry.RemoveAt(1); removes “United States” from the list, we can also use Remove() method to remove specific item from the list, for example lstCountry.Remove("United States");
1 2 3 4 5 6 7 8 9 10 11 12 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Removes a range of elements //This will remove "India" and "United States" from the list lstCountry.RemoveRange(0, 2); |
Use of RemoveRange() removes a range of items from the list, here we have used start index as 0 and number of elements removed as 2, which means “India” and “United States” will be removed from the list.
Read items in a List in C#
We can access or read elements in List using the index operator and for-each loop, C# is a zero-index based, hence index starts from 0. Lets have a look at below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Using foreach loop, we can traverse through a list and access each item Console.WriteLine("Read items in List using ForEach loop"); Console.WriteLine("**************************************"); foreach (string country in lstCountry) Console.WriteLine(country); Console.WriteLine("Read items in List using For loop and index value"); Console.WriteLine("**************************************"); for (int i = 0; i < lstCountry.Count; i++) Console.WriteLine(lstCountry[i]); |
When we run above code then it produces below output.
Complete Example Sample :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; using System.Collections.Generic; namespace ListCollectionExample { class Program { static void Main(string[] args) { //Creating a list of string objects List<string> lstCountry = new List<string>(); //Adding items to lstCountry object lstCountry.Add("India"); lstCountry.Add("United States"); lstCountry.Add("United Kingdom"); lstCountry.Add("Spain"); //Using foreach loop, we can travers through a list and access each item Console.WriteLine("Items in the List"); Console.WriteLine("**************************************"); foreach (string country in lstCountry) Console.WriteLine(country); Console.WriteLine("**************************************"); //Adding another list of items using AddRange method lstCountry.AddRange(new List<string>() { "Poland", "Greece", "Germany" }); //Adding a range of items Console.WriteLine("After Adding new range of list items \"Poland\",\"Greece\",\"Germany\""); Console.WriteLine("Items in the List"); Console.WriteLine("**************************************"); foreach (string country in lstCountry) Console.WriteLine(country); Console.WriteLine("**************************************"); //Adding an array of item to the list lstCountry.AddRange(new string[] { "Italy", "Brazil", "Peru", "Canada" }); Console.WriteLine("After Adding new range of aray of items \"Italy\",\"Brazil\",\"Peru\", \"Canada\""); Console.WriteLine("Items in the List"); Console.WriteLine("**************************************"); foreach (string country in lstCountry) Console.WriteLine(country); Console.WriteLine("**************************************"); //Removes a range of elements //This will remove "India" and "United States" from the list lstCountry.RemoveRange(0, 2); Console.WriteLine("After Removing \"India\" and \"United States\" from the list"); Console.WriteLine("Items in the List"); Console.WriteLine("**************************************"); foreach (string country in lstCountry) Console.WriteLine(country); } } } |
When we run above code then it produces below output.
Important methods and properties of List<T> type in C#
List<T>.Count : It is a property , used to get the number of elements present in a List<T>
1 2 3 4 |
//Creating a list of integer objects var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; //Get the total element count Console.WriteLine("Total Number Of Element : {0}" , lstNumbers.Count); //Prints Total Number Of Element : 6 |
List<T>.Clear() : It is a method , used to remove all from a List<T>
1 2 3 4 5 6 7 8 9 |
//Creating a list of integer objects var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; //Removes all elements from the list lstNumbers.Clear(); //We have removed all elements using Clear() function //Hence it prints Total Number Of Element : 0 Console.WriteLine("Total Number Of Element : {0}" , lstNumbers.Count); |
List<T>.Contains() : It is a method, that checks whether a specified item exists or not in a List<T>, it returns true if it exists or else false
1 2 3 4 5 |
//Creating a list of integer objects var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; bool isExist15 = lstNumbers.Contains(15);//Returns true bool isExist20 = lstNumbers.Contains(20);//Returns false |
List<T>.Insert() : Inserts an element at the specified index in a List<T>. It takes an index and value to insert.
1 2 3 4 5 |
//Creating a list of integer objects var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; //Inserts 20 at 2nd index: after 12. lstNumbers.Insert(2, 20); |
List<T>.Find() : It is a method, that finds first and single element based on the specified predicate function or a condition.
1 2 3 4 5 |
//Creating a list of integer objects var lstNumbers = new List<int>() { 11, 12, 13, 14, 15, 16 }; //This will return 13, since it is the first element in the list that is > 12 var item = lstNumbers.Find(x => x > 12); |
There are couple of other methods that are basically used for sorting and searching a List<T> , We will cover that in next article.
Thanks for your time, feel free to provide your feedback and do check my other blogs on Generics and Var Type in C#.