C# Lists

C# lists are a much easier way to manage data like an array, but with the ability to easily remove, add, and update each element. Be sure to check out C# Arrays if you have not already done so.

First off, a List uses System.Collections.Generic. You will need to add a using statement to the top of your class that uses a list. Example: using System.Collections.Generic;

A list can be defined by List<type> variableName = new List<type>();. The type can be a generic type such as string, boolean, int; Or you can use a type of a class model you have already defined. For this example we will be using the type of string to show how to implement a list of names.

So lets create a list of names. There is a few ways we can do this, so lets show how.

List<string> names = new List<string>();
names.Add("Todd");
names.Add("Jeff");
names.Add("Steve");

OR:

List<string> names = new List<string>()
        {
            "Todd",
            "Jeff",
            "Steve"
        };

If we want to get the number of items inside the list, we can use .Count. This will return the number of items which is useful for iteration in a for loop.

List<string> names = new List<string>()
{
    "Todd",
    "Jeff",
    "Steve"
};

Console.WriteLine(names.Count);

Now lets iterate through the loop

List<string> names = new List<string>()
{
    "Todd",
    "Jeff",
    "Steve"
};
foreach(string name in names)
{
    Console.WriteLine(name);
}

How do we add and remove the list?

To remove an item is simple. Simply just use .Remove();.
For example lets remove the first name of “Todd”.

List<string> names = new List<string>()
{
    "Todd",
    "Jeff",
    "Steve"
};

names.Remove("Todd");

foreach (string name in names)
{
    Console.WriteLine(name);
}

To add an item, we can use .Add(). So lets add another name

List<string> names = new List<string>()
{
    "Todd",
    "Jeff",
    "Steve"
};

names.Add("Bert");

foreach (string name in names)
{
    Console.WriteLine(name);
}

Also if we want to replace an item, we can do it just like arrays. We can iterate over each item and if the item is a match to the item we want to replace, then replace it.

List<string> names = new List<string>()
{
    "Todd",
    "Jeff",
    "Steve"
};

for(int i = 0; i < names.Count; i++)
{
    if(names[i] == "Jeff")
    {
        names[i] = "Bert";
    }
    Console.WriteLine(names[i]);
}

Leave a Reply

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