C# Generic List

A generic list is very similar to a non-generic arraylist, except that it is generic and therefore requires the data type of the elements stored within to be specified. They can grow and shrink automatically, whilst containing multiple null and duplicate values if necessary. A generic list is ideal for storing and retrieving large numbers of elements.

The example below creates a list of strings called ‘people’, adds four names, then, using a ‘foreach’ loop, displays the names in the console.

List<string> people = new List<string>();
people.Add("Bob");
people.Add("George");
people.Add("Fred");
people.Add("Alan");

foreach (string person in people)
{
    Console.WriteLine(person);
}

The output from this will be as follows.

Bob
George
Fred
Alan

The declaration and initialisation of the list can be done more efficiently by combining the two, whilst still allowing the ‘foreach’ loop to process the list in the same way.

List<string> people = new List<string>()
{
    "Bob",
    "George",
    "Fred",
    "Alan"
};

Note that, like with other collections, an ordinary ‘for’ loop could be used, but a ‘foreach’ loop is simpler.

As with other collections, each element in a generic list has an index value, which starts at zero for the first element. This can be used to access individual elements stored within. Here the second element with an index value of one is displayed in the console.

Console.WriteLine(people[1]);

If it is necessary to add an item into a generic list at a specific index position, this is possible using the 'Insert' method. The index position increases by one for all subsequent elements.

people.Insert(2, "Fiona");

In order to check if a value exists within a generic list, the 'Contains' method can be used. This returns a Boolean 'True' or 'False' value. This value is displayed out to the console in the below example, however, a more common use would be in 'if' statements.

Console.WriteLine(people.Contains("Bob"));

To place the elements within a generic list in order, there is a 'Sort' method that can be used to achieve this.

people.Sort();

In contrast to sorting the items in a generic list, it is also possible to randomise the order of them. To achieve this, a new list must be created to put the randomised values into.

List<string> shuffledPeople = people.OrderBy(x => Guid.NewGuid()).ToList();

As well as adding and inserting values, the index value can also be used to remove a specific element.

people.RemoveAt(2);

An alternative method of removing an element from a generic list is by specifying the value itself. Note that, if duplicate values exist, only the first occurrence of the specified value will be removed.

people.Remove("George");

Finally, if it is necessary to remove all items in a generic list in one go, instead of individually, there is a ‘Clear’ method to accomplish this.

people.Clear();

Further Reading