List in Practice
Add, remove, and search.
Why List<T>?
List<T> is the everyday dynamic array in C#. It lives in System.Collections.Generic and grows automatically as you add items.
Unlike a plain array, you never set a fixed size up front. It is type-safe: a List<int> only holds int values, caught at compile time.
using System.Collections.Generic;
List<int> scores = new List<int>();
scores.Add(90);
scores.Add(85);Creating and Initializing
You can fill a list right away using a collection initializer. This is concise and readable.
The compiler turns each entry into an Add call behind the scenes, so the result is identical to adding items one by one.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var fruits = new List<string> { "apple", "pear", "plum" };
Console.WriteLine(fruits.Count);
}
}All lessons in this course
- List in Practice
- Dictionary Lookups
- HashSet and Uniqueness
- Choosing a Collection