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
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);
}
}
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.
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
}
}
You can also add a whole array to a list using the AddRange
function.
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int>();
int[] array = new int[] { 1, 2, 3 };
numbers.AddRange(array);
}
}
Removing From a List
We can use Remove()
to remove an item from a list by specifying the item we want to remove.
class Program
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
// add fruits
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("orange");
// now remove the banana
fruits.Remove("banana");
Console.WriteLine(fruits.Count);
}
}
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.
class Program
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
// add fruits
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("orange");
// now remove the banana
fruits.RemoveAt(1);
Console.WriteLine(fruits.Count);
}
}
Concatenating Lists
class Program
{
static void Main(string[] args)
{
List<string> food = new List<string>();
food.Add("apple");
food.Add("banana");
List<string> vegetables = new List<string>();
vegetables.Add("tomato");
vegetables.Add("carrot");
food.AddRange(vegetables);
Console.WriteLine(food.Count);
}
}
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