C# List

C# List represents a collection of strongly typed objects. Learn here to use List<T> class in C# to work with collections.

The C# List<T> class in .NET represents a collection of strongly typed objects that can be accessed by index. In this tutorial, we learn how to use the C# List class to add, find, sort, reverse, and search items in a collection of objects using List class methods and properties.

C# List<T> Class

List<T> class in C# represents a strongly typed list of objects. List<T> provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List<T>, T is the type of objects.

What is the ‘T’ in List<T>? 

List<T> class in represents a strongly typed list of objects. List<T> provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List<T>, T is the type of objects. 

Creating List<T> object 

List<T> is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List<T> class.

  1. using System.Collections.Generic;  

List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object. 

The code snippet in Listing 1 creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.

  1. // List with default capacity  
  2. List<Int16> list = new List<Int16>();  
  3. // List with capacity = 5  
  4. List<string> authors = new List<string>(5);  
  5. string[] animals = { "Cow""Camel""Elephant" };  
  6. List<string> animalsList = new List<string>(animals);  

Listing 1.

As you can see from Listing 1, the List<string> has an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands. 

Adding Items to a C# List 

The Add method adds an element to a List. The code snippet in Listing 2 creates two List<T> objects and adds integer and string items to them respectively.

  1. // Dynamic ArrayList with no size limit  
  2. List<int> numberList = new List<int>();  
  3. numberList.Add(32);  
  4. numberList.Add(21);  
  5. numberList.Add(45);  
  6. numberList.Add(11);  
  7. numberList.Add(89);  
  8. // List of string  
  9. List<string> authors = new List<string>(5);  
  10. authors.Add("Mahesh Chand");  
  11. authors.Add("Chris Love");  
  12. authors.Add("Allen O'neill");  
  13. authors.Add("Naveen Sharma");  
  14. authors.Add("Monica Rathbun");  
  15. authors.Add("David McCarter");

Listing 2.

We can also add a collection to a List. The AddRange method is used to add a collection to a List. The code snippet in Listing 3 adds an array of strings to a List.

  1. // Collection of string  
  2. string[] animals = { "Cow""Camel""Elephant" };  
  3. // Create a List and add a collection  
  4. List<string> animalsList = new List<string>();  
  5. animalsList.AddRange(animals);  
  6. foreach (string a in animalsList)  
  7. Console.WriteLine(a);  
  8.    

Listing 3.

Reading a List Items In C# 

List is a collection of items. We can use a foreach loop to loop through its items. The code snippet in Listing 6 reads all items of a List and displays on the console.

  1. foreach (string a in authors)  
  2. Console.WriteLine(a);  

Listing 4. 

The output of Listing 4 looks like Figure 1. 

Figure 1. 

To retrieve an item at a specific position in the List, we can use the collection’s index. The following code snippet reads the 3rd items in the List.

  1. Console.WriteLine(authors[2]);  

List Class Properties 

List class properties include the following:

  • Capacity – Number of elements List<T> can contain. The default capacity of a List<T> is 0.
  • Count – Number of elements in List<T>.

Code snippet in Listing 5 gets the value of these properties.

  1. ArrayList authorsArray = new ArrayList();  
  2. authorsArray.Add("Mahesh Chand");  
  3. authorsArray.Add("Praveen Kumar");  
  4. authorsArray.Add("Raj Kumar");  
  5. authorsArray.Add("Dinesh Beniwal");  
  6. authorsArray.Add("David McCarter");  
  7. Console.WriteLine("Count: " + authors.Count);  
  8. Console.WriteLine("Capacity: " + authors.Capacity);  

Listing 5.

Insert Items at a Position in a C# List 

The Insert method of List class inserts an object at a given position. The first parameter of the method is the 0th based index in the List.

The InsertRange method can insert a collection at the given position. 

The code snippet in Listing 6 inserts a string at the 3rd position and an array at the 2nd position of the List<T>.

  1. authors.Insert(3, "Bill Author");  
  2. // Collection of new authors  
  3. string[] newAuthors = { "New Author1""New Author2""New Author3" };  
  4. // Insert array at position 2  
  5. authors.InsertRange(2, newAuthors);  
Listing 6.

Remove Items of a C# List

The List class provides Remove methods that can be used to remove an item or a range of items. 

The Remove method removes the first occurrence of the given item in the List. The following code snippet removes the first occurrence of ‘New Author1’.

  1. // Remove an item  
  2. authors.Remove("New Author1"); 

The RemoveAt method removes an item at the given position. The following code snippet removes the item at the 3rd position.

  1. // Remove 3rd item  
  2. authors.RemoveAt(3);

The RemoveRange method removes a list of items from the starting index to the number of items. The following code snippet removes two items starting at 3rd position.

  1. // Remove a range  
  2. authors.RemoveRange(3, 2);  

The Clear method removes all items from a List<T>. The following code snippet removes all items from a List.

  1. // Remove all items  
  2. authors.Clear();  

Find an Item in a C# List

The IndexOf method finds an item in a List. The IndexOf method returns -1 if there are no items found in the List. 

The following code snippet finds a string and returns the matched position of the item.

  1. int idx = authors.IndexOf("Naveen Sharma");  
  2. if (idx > 0)  
  3. Console.WriteLine($"Item index in List is: {idx}");  
  4. else  
  5. Console.WriteLine("Item not found");  

We can also specify the position in a List where IndexOf method can start searching from. 

For example, the following code snippet finds a string starting at the 3rd position in a String.

  1. Console.WriteLine(authors.IndexOf("Naveen Sharma", 2));  

The LastIndexOf method finds an item from the end of List. 

The following code snippet looks for a string in the backward direction and returns the index of the item if found.

  1. Console.WriteLine(authors.LastIndexOf("Mahesh Chand"));  

The complete example is listed in Listing 7.

  1. // List of string  
  2. List<string> authors = new List<string>(5);  
  3. authors.Add("Mahesh Chand");  
  4. authors.Add("Chris Love");  
  5. authors.Add("Allen O'neill");  
  6. authors.Add("Naveen Sharma");  
  7. authors.Add("Mahesh Chand");  
  8. authors.Add("Monica Rathbun");  
  9. authors.Add("David McCarter");  
  10. int idx = authors.IndexOf("Naveen Sharma");  
  11. if (idx > 0)  
  12. Console.WriteLine($"Item index in List is: {idx}");  
  13. else  
  14. Console.WriteLine("Item not found");  
  15. Console.WriteLine(authors.IndexOf("Naveen Sharma", 2));  
  16. Console.WriteLine(authors.LastIndexOf("Mahesh Chand"));  

Listing 7.  

Sort a C# List Items 

The Sort method of List<T> sorts all items of the List using the QuickSort algorithm. 

The following code example in Listing 8 sorts a List items and displays both original order and sorted order of the List items.

  1. // List of string  
  2. List<string> authors = new List<string>(5);  
  3. authors.Add("Mahesh Chand");  
  4. authors.Add("Chris Love");  
  5. authors.Add("Allen O'neill");  
  6. authors.Add("Naveen Sharma");  
  7. authors.Add("Mahesh Chand");  
  8. authors.Add("Monica Rathbun");  
  9. authors.Add("David McCarter");  
  10. Console.WriteLine("Original List items");  
  11. Console.WriteLine("===============");  
  12. // Print original order  
  13. foreach (string a in authors)  
  14. Console.WriteLine(a);  
  15. // Sort list items  
  16. authors.Sort();  
  17. Console.WriteLine();  
  18. Console.WriteLine("Sorted List items");  
  19. Console.WriteLine("===============");  
  20. // Print sorted items  
  21. foreach (string a in authors)  
  22. Console.WriteLine(a);

Listing 8. 

The output of Listing 8 looks like Figure 2. 

 

Figure 2. 

Reverse an ArrayList 

The Reverse method of List<T> reverses the order all items in in the List. 

The following code snippet reverses a List.

  1. // List of string  
  2. List<string> authors = new List<string>(5);  
  3. authors.Add("Mahesh Chand");  
  4. authors.Add("Chris Love");  
  5. authors.Add("Allen O'neill");  
  6. authors.Add("Naveen Sharma");  
  7. authors.Add("Mahesh Chand");  
  8. authors.Add("Monica Rathbun");  
  9. authors.Add("David McCarter");  
  10. Console.WriteLine("Original List items");  
  11. Console.WriteLine("===============");  
  12. // Print original order  
  13. foreach (string a in authors)  
  14. Console.WriteLine(a);  
  15. // Reverse list items  
  16. authors.Reverse();  
  17. Console.WriteLine();  
  18. Console.WriteLine("Sorted List items");  
  19. Console.WriteLine("===============");  
  20. // Print reversed items  
  21. foreach (string a in authors)  
  22. Console.WriteLine(a);  
Listing 9. 

The output of Listing 9 looks like Figure 3. 

 

Figure 3. 

Search a C# List

The BinarySearch method of List<T> searches a sorted list and returns the zero-based index of the found item. The List<T> must be sorted before this method can be used. 

The following code snippet returns an index of a string in a List.

  1. int bs = authors.BinarySearch("Mahesh Chand");  

Summary 

This article demonstrated how to use a List<T> class to work with a collection of objects. The article also demonstrated how to add, find, search, sort, and reverse items in a List.