Unlock the Power of Lists in C#
What is a List
A List
Getting Started with List
To create a List
List<int> numbers = new List<int> { 1, 2, 3 };
Accessing List Elements
Now that you have a List, how do you access its elements? Easy! Use index notation []
to retrieve the desired element. Remember, the index starts at 0, so language[0]
accesses the first element, while language[5]
accesses the sixth element.
Iterating Through the List
Need to loop through each element of your List? No problem! A simple for
loop does the trick. For example:
for (int i = 0; i < albums.Count; i++) { Console.WriteLine(albums[i]); }
Basic Operations on List
The List
Adding Elements
Use the Add()
method to add a single element to your List. For example:
country.Add("USA");
Inserting Elements
Insert an element at a specified index using the Insert()
method. For example:
languages.Insert(2, "JavaScript");
Removing Elements
Delete one or more items from your List using the Remove()
or RemoveAt()
methods. For example:
car.Remove("Tesla");
or car.RemoveAt(2);
Frequently Asked Questions
Did you know you can create a List using the var
keyword? For example:
var languages = new List<string> { "C#", "Java", "Python" };
Now you’re equipped to harness the power of Lists in C#!