C# 11 List Collections

In the previous chapters, we looked at C# Arrays. While useful for many tasks, arrays are starting to show their age in terms of functionality and flexibility. The C# Collection Classes provide more advanced mechanisms for gathering groups of objects.

What are the C# Collection Classes

The C# Collection classes are designed specifically for grouping objects and performing tasks on them. Several collection classes are available with C#, and we will look at some key classes in the next few chapters.

Creating C# List Collections with List<T>

The List<T> class has properties very similar to C# arrays. One key advantage of this class over arrays is that it can grow and shrink as the number of stored objects changes.

The List<T> class is contained within the  System.Collections.Generic  namespace, which must be imported when working with lists.

The syntax for creating a List<T> collection is as follows where type is replaced by the data type to be stored in the list:

List<type> name = new List<type>(); 

With the above syntax in mind, we could create an empty List<T> object named colorList configured to store string values as follows:

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

Adding items to lists

Once you have created a List object instance, there are several methods you can call to perform tasks on the list. One such method is the Add() method which, as the name suggests, is used to add items to the list object:

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

colorList.Add ("Red");
colorList.Add ("Green");
colorList.Add ("Yellow");
colorList.Add ("Purple");
colorList.Add ("Orange");

The Add() method appends the new item to the end of the list. To insert new items at a specific index location, you will need to use the Insert() method covered later in the chapter.

Initializing a list with multiple values

In the above example, we created an empty list and then added items one by one using the Add() method. However, if you need to initialize a list with a large number of values, you may find it more efficient to use a collection initializer, the syntax for which is as follows:

List<type> <list-name> = new List<type>()
{
    <item1>,
    <item2>,
    <item3>,
.
.
.
};

Using this syntax, we can modify our initialization example as follows:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

Accessing list items

Individual items in a list may be accessed using the item’s index value (keeping in mind that the first item is index 0, the second index 1, and so on). The index value is placed in square brackets after the list name. For example, to access the second item in the colorList object:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine (colorList[1]);

Output:

Green

A list item value can similarly be changed using the index combined with the assignment (=) operator. For example, to change the Yellow color to Ingido, the code would read as follows:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine ($"Color before = {colorList[2]}");
colorList[2] = "Indigo";
System.Console.WriteLine ($"Color after = {colorList[2]}");

Output:

Color before = Yellow
Color after = Indigo

As with arrays, you can also construct a foreach loop to list all of the items in a list. For example:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

foreach (string color in colorList)
{
    System.Console.Write($"{color} ");
}

Output:

Red Green Yellow Purple Orange

Removing items from lists

Items may be removed from a list using the Remove() method. This method takes the value of the item to be removed as an argument. For example, to remove the “Red” string from the colorList object, we could write the following code:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

colorList.Remove("Red");

foreach (string color in colorList)
{
    System.Console.Write($"{color} ");
}

Output:

Green Yellow Purple Orange

Note: C# liscan to store duplicate entries. In the case of duplicated items, the Remove() method will only remove the first matching instance.

Inserting items into a list

Previously we used the Add() method to add items to a list. The Add() method, however, only adds items to the end of a list. Sometimes it is necessary to insert a new item at a specific location in a list. The Insert() method is provided for this particular purpose.

Insert() takes two arguments, an integer indicating the index location of the insertion and the item to be inserted at that location. For example, to insert an item at location 2 in our example list:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

colorList.Insert(2, "White");

foreach (string color in colorList)
{
    System.Console.Write($"{color} ");
}

Output:

Red Green White Yellow Purple Orange 

Sorting lists in C#

There is no way to tell C# to automatically sort a list as items are added. The items in a list can be sorted into order by calling the Sort() method:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

colorList.Sort();

foreach (string color in colorList)
{
    System.Console.Write($"{color} ");
}

Output:

Green Orange Purple Red Yellow 

The above example uses the C# default comparison delegate to organize the new list order. Although beyond the scope of this book, it is worth knowing that for more advanced requirements, you can create your own comparison delegate.

Finding items in a C# list

Several methods are provided with the List class for finding items. The most basic method is the Contains() method which, when called on a list object, returns true if the specified item is located in the list, or false if it is not.

The IndexOf() method returns the index value of a matching item in a list. For example, the following code sample will output a true result indicating the presence of “Red” and the value 2, which is the index position of the “Yellow” string:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine(colorList.Contains("Red"));
System.Console.WriteLine(colorList.IndexOf("Yellow"));

Output:

True
2Code language: PHP (php)

If the item is not found in the list, a value of -1 is returned by the  IndexOf()  method.

The LastIndexOf() method returns the index value of the last item in the list to match the specified item. This is particularly useful when a list contains duplicate items:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Red",
    "Orange"
};

System.Console.WriteLine(colorList.LastIndexOf("Red"));

Output:

4

Obtaining information about a list

Two properties of the List<T> class are helpful in obtaining information about a list object. For example, the Capacity property can identify how many items a collection can store without resizing.

The Count property, however, identifies how many items are currently stored in the list. In general, the Capacity value will exceed the current Count:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine($"Count = {colorList.Count}");
System.Console.WriteLine($"Capacity = {colorList.Capacity}");

Output:

Count = 5
Capacity = 8

In instances where a gap exists between Count and Capacity you can remove excess capacity with a call the TrimExcess() method:

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine($"Count = {colorList.Count}");
colorList.TrimExcess();
System.Console.WriteLine($"Capacity = {colorList.Capacity}");

Output:

Count = 5
Capacity = 5

Clearing C# lists

You can remove all of the items in a list by making a call to the Clear() method.

The Clear() method removes the items from the list and sets the  Count  property to zero. The Capacity property, however, remains unchanged after the list has been cleared. To remove the capacity of a list, follow the Clear() method call with a call to TrimExcess():

List<string> colorList = new List<string>()
{
    "Red",
    "Green",
    "Yellow",
    "Purple",
    "Orange"
};

System.Console.WriteLine($"Count = {colorList.Count}");
System.Console.WriteLine($"Capacity = {colorList.Capacity}");

colorList.Clear();

System.Console.WriteLine($"Count = {colorList.Count}");
System.Console.WriteLine($"Capacity = {colorList.Capacity}");

colorList.TrimExcess();

System.Console.WriteLine($"Count = {colorList.Count}");
System.Console.WriteLine($"Capacity = {colorList.Capacity}");

Output:

Count = 5
Capacity = 8
Count = 0
Capacity = 8
Count = 0
Capacity = 0

Categories