- The List is just like the ArrayList except the later is non-generic.
- The arrays are fixed size while List <T> can grow as needed automatically.
- Other generic classes in the System.Collection.Generic Namespace includes Dictionary, Queue, and Stack.
- A list is created by using the new keyword as shown in the example in the next section.
- The index of the list starts at 0.
- You may use Add method of the List class to add new elements at the end of a list.
lst_numbers.Add(1); lst_numbers.Add(3); lst_numbers.Add(5);
- For removing all elements from the list, you may use the Clear method.
- For adding a new element at the specified position, use the Insert method of the List class.
- For removing a specified element from the list, use the Remove method.
- To sort a list, the List class has the Sort method.
- The section below explains how to create, initialize, and iterate through lists. You may also see examples of a few useful list methods.
- 1. How to create/declare a List<T> in C#?
- 2. Initializing a list
- 3. Adding elements to a list by Add method
- 4. How to insert an item at the specified index by the Insert method
- 5. The example of adding multiple items by InsertRange method
- 6. An example of sorting a List<T> by the sort method
- 7. How to remove a List<T> item? The Remove method
- 8. Removing all occurrences of the specified element by RemoveAll method
- 9. Using Clear method for removing all elements in a List<T>
- 10. How to search in C# List<T>?
- 11. The example of Contains method
- 12. How to use Find method of List<T>?
- 13. Using Exists method for searching element(s) in List<T>
How to create/declare a List<T> in C#?
The syntax for creating a List<T>:
In the above syntax, we created a list namely list_name of the type int. Similarly, you may create a list of string as follows:
Initializing a list
You may use the add method of the list class to add new elements to the list after its declaration. However, you may also create elements at the time of declaration in the list.
For example, we have a List of type string with three elements at the time of declaration as follows:
The following simple code shows declaring, initializing, and accessing a list element:
using System; using System.Collections.Generic; class List_Demos { static void Main() { List<string> str_list = new List<string>(new string[] { "string1", "string2", "string3" }); System.Console.WriteLine(str_list[1]); Console.ReadLine(); } }
The output of the above example should be:
As such, the index of a list starts at zero.
Adding elements to a list by Add method
In the example of the List Add method, I have created a list of int type. This is followed by using the Add method for adding five elements to the list.
Finally, I used the foreach statement for iterating through the list and displayed the List<T> elements:
using System; using System.Collections.Generic; class List_Demos { static void Main() { List<int> lst_numbers = new List<int>(); lst_numbers.Add(1); lst_numbers.Add(3); lst_numbers.Add(5); lst_numbers.Add(7); lst_numbers.Add(9); foreach (int num in lst_numbers) { System.Console.WriteLine("The List element = " +num); } Console.ReadLine(); } }
The output:
How to insert an item at the specified index by the Insert method
Rather than adding an element at the end of a List<T> you may add an element at the specified index. For that, you may use the Insert method of the List<T> class.
The general syntax of using the Insert method is:
In this example, a List<T> of int items is created initially with five elements. Then a foreach statement is used to display the List<T>.
This is followed by using the Insert method and I added a new element at the 3 index (starting at 0).
Again, I used the foreach and displayed the list elements and you can see the order of new element:
using System; using System.Collections.Generic; class List_Insert_Demo { static void Main() { List<int> lst_num_Ins = new List<int>(); lst_num_Ins.Add(1); lst_num_Ins.Add(3); lst_num_Ins.Add(5); lst_num_Ins.Add(7); lst_num_Ins.Add(9); System.Console.WriteLine("List before Insert method"); foreach (int num in lst_num_Ins) { System.Console.WriteLine(num); } lst_num_Ins.Insert(3, 13); System.Console.WriteLine("List after Insert method"); foreach (int num in lst_num_Ins) { System.Console.WriteLine(num); } Console.ReadLine(); } }
The number 13 is displayed at 3 index.
The example of adding multiple items by InsertRange method
The syntax for using the InsertRange method is:
So, you may specify the index position where you want to start inserting new elements from another collection.
To demonstrate that, the following example creates a list and an array. After creating the array, its elements are added to the list as shown in the example below:
using System; using System.Collections.Generic; class List_InsertRange_Demo { static void Main() { List<string> lst_str = new List<string>(); lst_str.Add("This"); lst_str.Add("is"); lst_str.Add("list"); lst_str.Add("Items"); System.Console.WriteLine("************Before InsertRange**********"); foreach (string val in lst_str) { System.Console.WriteLine(val); } //Declaring and initializing an array string[] Arr_in_lst = new string[] { "The", "Array", "Elements"}; //Using InsertRange method lst_str.InsertRange(2, Arr_in_lst); System.Console.WriteLine("*************After InsertRange***********"); foreach (string val2 in lst_str) { System.Console.WriteLine(val2); } Console.ReadLine(); } }
The output of the above program:
An example of sorting a List<T> by the sort method
For using the sort method, simply use the list name that you want to sort followed by the sort() keyword.
In the following example, we have a random list of integer elements. The list items are displayed before and after using the sort() method.
Have a look at the code and output:
using System; using System.Collections.Generic; class List_Sort_Demo { static void Main() { List<int> lst_num_sort = new List<int>(); lst_num_sort.Add(11); lst_num_sort.Add(31); lst_num_sort.Add(5); lst_num_sort.Add(7); lst_num_sort.Add(9); lst_num_sort.Add(15); lst_num_sort.Add(1); lst_num_sort.Add(3); System.Console.WriteLine("*************Before Sorting***********"); foreach (int num in lst_num_sort) { System.Console.WriteLine(num); } lst_num_sort.Sort(); System.Console.WriteLine("\n" + "*************After Sorting***********" + "\n"); foreach (int num in lst_num_sort) { System.Console.WriteLine(num); } Console.ReadLine(); } }
The result:
How to remove a List<T> item? The Remove method
The syntax of using the Remove method is:
If the item is found, the Remove method returns true, otherwise false.
See the following example where we have a list of following numbers:
The Remove() method is used to delete the element 5 from the list. See the code and result:
using System; using System.Collections.Generic; class List_Remove_Demo { static void Main() { List<int> lst_Remove = new List<int>(); lst_Remove.Add(1); lst_Remove.Add(5); lst_Remove.Add(11); lst_Remove.Add(21); lst_Remove.Add(5); lst_Remove.Add(15); System.Console.WriteLine("*************List Before Remove***********"); foreach (int num in lst_Remove) { System.Console.WriteLine(num); } lst_Remove.Remove(5); System.Console.WriteLine("\n" + "*************List After Remove***********" + "\n"); foreach (int num in lst_Remove) { System.Console.WriteLine(num); } Console.ReadLine(); } }
The Result:
You can see, the List<T> contains 5 two times. However, the Remove() method deleted only the first occurrence.
Removing all occurrences of the specified element by RemoveAll method
- The example below shows using the RemoveAll method for deleting all occurrences of the item in the specified List<T>.
- I am using the same list items as in the above example i.e. occurrences of item 5 two times.
- See the output before and after using the RemoveAll method:
using System; using System.Collections.Generic; class List_RemoveAll_Demo { static void Main() { List<int> lst_RemoveAll = new List<int>(); lst_RemoveAll.Add(1); lst_RemoveAll.Add(5); lst_RemoveAll.Add(11); lst_RemoveAll.Add(21); lst_RemoveAll.Add(5); lst_RemoveAll.Add(15); System.Console.WriteLine("*************List Before RemoveAll***********"); foreach (int num in lst_RemoveAll) { System.Console.WriteLine(num); } lst_RemoveAll.RemoveAll(item => item == 5); System.Console.WriteLine("\n" + "*************List After RemoveAll***********" + "\n"); foreach (int num in lst_RemoveAll) { System.Console.WriteLine(num); } Console.ReadLine(); } }
The Output:
The output shows the occurrence of 5 is removed twice.
Using Clear method for removing all elements in a List<T>
If you require removing all elements from the list in a single call then use the Clear() method.
The Clear() method is simple to use i.e.:
The example below shows a list before and after using the clear method:
using System; using System.Collections.Generic; class List_Clear_Demo { static void Main() { List<int> lst_Clear = new List<int>(); lst_Clear.Add(100); lst_Clear.Add(500); lst_Clear.Add(1100); System.Console.WriteLine("*************List Before Clear***********"); foreach (int num in lst_Clear) { System.Console.WriteLine(num); } lst_Clear.Clear(); System.Console.WriteLine("\n" + "*************List After Clear***********" + "\n"); foreach (int num in lst_Clear) { System.Console.WriteLine(num); } Console.ReadLine(); } }
You can see the list is empty after using the Clear() method.
How to search in C# List<T>?
For searching element(s) in lists, you may use several methods. The following methods are available in C#:
- Contains
- Find
- Exists
Each of these methods is explained below with an example.
The example of Contains method
The following simple example shows how to use the Contains method:
using System; using System.Collections.Generic; class List_Contains { static void Main() { List<string> lst_demo = new List<string>(); lst_demo.Add("C#"); lst_demo.Add("C Sharp"); lst_demo.Add("Tutorials"); if (lst_demo.Contains("Tutorials")) { System.Console.WriteLine("The item Tutorials exists in the List<T>"); } else { System.Console.WriteLine("The item Tutorials does not exist in the List<T>"); } Console.ReadLine(); } }
The output of the above code is:
How to use Find method of List<T>?
The general syntax for using the Find method:
By using the Find method, you may search a list for items based on the condition that is defined by the specified predicate.
The Find method returns the first occurrence in the entire List<T>.
To show how it works, see the example below.
We have a string list of six items. The fruit “Mango” is used two times in the List<T>. See how the Find method is used with lambda expression and the result:
using System; using System.Collections.Generic; class List_Find { static void Main() { List<string> lst_Find = new List<string>(); lst_Find.Add("Mango"); lst_Find.Add("Apple"); lst_Find.Add("Banana"); lst_Find.Add("Pine Apple"); lst_Find.Add("Strawberry"); lst_Find.Add("Apple"); string str_result = lst_Find.Find(X => X == "Mango"); System.Console.WriteLine(str_result); Console.ReadLine(); } }
The result:
Learn more about the Find method here.
Using Exists method for searching element(s) in List<T>
The general syntax for using the Exists method is:
The following example shows using the Exists method:
using System; using System.Collections.Generic; class List_Find { static void Main() { List<int> lst_Exists = new List<int>(); lst_Exists.Add(1); lst_Exists.Add(3); lst_Exists.Add(5); lst_Exists.Add(7); lst_Exists.Add(9); bool bool_result1 = lst_Exists.Exists(X => X > 10 ); bool bool_result2 = lst_Exists.Exists(X => X < 10); System.Console.WriteLine(bool_result1); System.Console.WriteLine(bool_result2); Console.ReadLine(); } }
The output of the code:
False
True