4.3 List

The difference between a list and an array is that lists are dynamic, while arrays have a fixed size. When you do not know the amount of variables your array should hold, use a list instead.

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it Lists

Visualization

 class Program
    {
        static void Main(string[] args)
        {
//          1     2     3         4
            List<int> numbers = new List<int>();
//          5 
            numbers.Add(1);
            numbers.Add(2);
            numbers.Add(3);
        }
    }
  1. Declaring that you are building a list

  2. The datatype your list will hold

  3. The name of your list

  4. Initializing a new list

  5. Adding values to your list using the function .Add()

Initializing a List

A List can be initialized with a variable of List<int>;. List can use any of the data types used within C#. Then you go on to name your list and instantiate it. It should look something like this:

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

Adding Values To Your List

We use an Add() method after the list's name to add values into a list.

You can also add a whole array to a list using the AddRange function.

Removing From a List

We can use Remove() to remove an item from a list by specifying the item we want to remove.

We can also use RemoveAt() to specify an index of an item to remove. In our case, to remove the banana, we will use the index 1.

Concatenating Lists

Challenge

Bronze Challenge

  • Use the C# List type to make a string list of 10 phone numbers

  • Make the numbers 317.555.0001 all the way up to 317.555.0010

  • Print the 10 numbers to the console by ITERATING over the list

Silver Challenge

  • Let's pretend that Paul's phone number is 317.555.0005

  • Loop through the list and print that number with the message "Paul's phone number is 317.555.0005

  • Do the same with another person's number, except theirs ends with 0007

    Answers

    Next: More about OOP

Last updated