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
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Lists
Visualization
Declaring that you are building a list
The datatype your list will hold
The name of your list
Initializing a new list
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
Last updated