C# – Lists

In C#, a list is a variable that is able to store multiple values of the same type and those values can be accessed by an index. This is similar to arrays which were covered in the previous post. However, unlike arrays, the size of the list does not need to be set at declaration and list size can grow dynamically. Also, list have methods that can be used to search, sort, and manipulate the list.

Declaring A List

Lists are defined in the System.Collections.Generic namespace so to use a list this namespace needs to be added to the project using the below line of code.

using System.Collections.Generic;

Below is an example of how to declare a list of type integers.

List<int> intList = new List<int>();

The above example works like this:

  1. We start by using the List keyword to let the compiler know this variable will be a list.
  2. Next to the List keyword are angle brackets (<>). The data type that the list will hold is specified by putting the data type of int in the angle brackets.
  3. intList is the name of the variable.
  4. The new keyword followed by List<int>() tells the compiler to create a list that will hold integers.
  5. The list of integers is assigned to the intList variable.

The below example shows how to create a list of strings:

List<string> strList = new List<string>();

Assigning Values To The List During Declaration

If you know values that need to be added to the list during declaration then you can add the collection initializer to the end of the declaration statement. A collection initializer is the curly braces {} with values separated by commas inside of the curly braces. The example below shows a list variable of names that is assigned strings during declaration.

List<string> names = new List<string>() { "John", "Mary", "Bob", "Sally" };

The screenshot below shows this list variable in the Visual Studio debugger. From the screenshot, you can see that the strings are assigned to indexes of the list similar to how arrays work. It is also important to note that like arrays, list start with an index of 0.

Adding Values To List

The Add() method is used do add elements to a list. When the Add() method is used the element will be added to the end of the list. The code below shows an example of using the Add() method.

List<int> intList = new List<int>();
intList.Add(1);
intList.Add(2);
intList.Add(3);
intList.Add(4);

The screenshot below shows the intList variable from the above code in the Visual Studio debugger.

The below code shows an example of adding characters to a list.

List<char> charList = new List<char>();
charList.Add('a');
charList.Add('b');
charList.Add('c');
charList.Add('d');

Removing Elements From A List

Remove() Method

The Remove() method will remove the first occurrence of the element that is passed into this method. An example of the Remove() method is below.

List<int> intList = new List<int>() { 1, 2, 3, 1, 2, 3};
intList.Remove(1);

In the above example, the Remove(1) method searches for the first element with a value of 1 and removes it from the list. The below screenshot is from Visual Studio debugger after using the Remove(1) method. You can see that the index of 0 now has a value of 2 where a value of 1 would have previously been. Also, at index 2 there is still a value of 1 because that was a second occurrence of 1 in this list.

RemoveAt() Method

The RemoveAt() method is used to remove a value at a specific index of the list.

List<int> intList = new List<int>() { 1, 2, 3 };
intList.RemoveAt(1);

In the above example, after running RemoveAt(1) the value of 2 at index 1 is removed and the list now contains 1 at index 0 and 3 at index 1 as shown in the Visual Studio debugger screenshot below.

Clear() Method

The Clear() method removes all elements from a list. No parameter is passed into the Clear method.

intList.Clear();

Accessing Elements Of A List

To access the elements of a list you need to follow the list variable name with brackets ([]) and put the number of the index in the brackets.

List<int> intList = new List<int>() { 1, 2, 3};
Console.WriteLine( intList[0] );
Console.WriteLine( intList[2] );

The above code prints the element at index 0 and index 2 so it will have the following output:
1
3

Looping Through A List With A for Loop

When using a for loop to loop through an entire list, the Count property is used to get the size of list to be used in the condition to stop the loop. The below code is an example of using a for loop to with a list.

List<int> intList = new List<int>() { 1, 2, 3, 4};
for (int i = 0; i < intList.Count; i++)
{
     Console.WriteLine( intList[i] );
}

The above code uses a for loop that sets the variable i to 0 to access the first element of the list and then accesses each element of the list until the loop ends when i is incremented to the size of the list. The above code would have the following output:
1
2
3
4

Looping Through A List With A foreach Loop

A foreach loop can be used to loop through a list without using an index. The below code is an example of using a foreach loop to loop through a list.

List<int> intList = new List<int>() { 1, 2, 3, 4};
foreach (var item in intList)
{
     Console.WriteLine( item );
}

In the above example, the item variable is assigned to the current element of the iteration of the loop. The above code would have the following output:
1
2
3
4

Sorting List

Sort() Method

The Sort() method sorts the elements of a list in ascending order. Below is an example of sorting elements of an integer list.

List<int> intList = new List<int>() { 4, 1, 3, 2 };

intList.Sort();

foreach (var item in intList)
{
     Console.WriteLine(item);
}

The above code has the following output:
1
2
3
4

Below is an example of sorting a list of strings in ascending order.

List<string> strList = new List<string>() { "John", "Mary", "Bob", "Sally" };

strList.Sort();

foreach (var item in strList)
{
     Console.WriteLine(item);
}

The above code has the following output:
Bob
John
Mary
Sally

Reverse() Method

The Reverse() method reverses the elements of a list. Below is an example of reverse sorting elements of an integer list.

List<int> intList = new List<int>() { 1, 2, 3, 4 };

intList.Reverse();

foreach (var item in intList)
{
     Console.WriteLine(item);
}

The above code would have the following output:
4
3
2
1

Below is an example of reverse sorting a list of strings.

List<string> strList = new List<string>() { "John", "Mary", "Bob", "Sally" };

strList.Reverse();

foreach (var item in strList)
{
     Console.WriteLine(item);
}

The above code would have the following output:
Sally
Bob
Mary
John

Conclusion

A list is a type of variable that can hold multiple values of the same type. The size of a list does not need to be set at declaration. The size of a list grows dynamically as elements are added to it.


References:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0
https://www.youtube.com/watch?v=gXyoJA579QI
https://www.youtube.com/watch?v=2DKvOREiLBg
https://www.c-sharpcorner.com/article/c-sharp-list/

Leave a Comment

Your email address will not be published. Required fields are marked *