C# List

A List<T> is the modern, type-safe version of a dynamic collection in C#. It is part of the System.Collections.Generic namespace. Unlike arrays, it grows and shrinks automatically. Unlike ArrayList, it stores only one specific type — no accidental mixing of strings and numbers.

Why List Over Array?

┌──────────────────────────────┬──────────────────────────────┐
│ Array                        │ List<T>                      │
├──────────────────────────────┼──────────────────────────────┤
│ Fixed size                   │Grows and shrinks dynamically │
├──────────────────────────────┼──────────────────────────────┤
│ No built-in Add/Remove       │ Add(), Remove(), Insert()    │
├──────────────────────────────┼──────────────────────────────┤
│ Ideal for known-size data    │ Ideal for unknown-size data  │
└──────────────────────────────┴──────────────────────────────┘

Creating a List

using System;
using System.Collections.Generic;

// Empty list of integers
List<int> numbers = new List<int>();

// Empty list of strings
List<string> names = new List<string>();

// List initialized with values
List<string> fruits = new List<string>() { "Apple", "Mango", "Banana" };

Adding and Inserting Items

List<string> cities = new List<string>();

cities.Add("London");        // adds to the end
cities.Add("Tokyo");
cities.Add("Paris");

cities.Insert(1, "Sydney");  // inserts at index 1

// Result: [London, Sydney, Tokyo, Paris]

// Diagram:
// Before Insert(1, "Sydney"):
//   [London] [Tokyo] [Paris]
//      0        1       2
//
// After Insert(1, "Sydney"):
//   [London] [Sydney] [Tokyo] [Paris]
//      0        1        2       3

AddRange() — Add Multiple Items

List<int> scores = new List<int>() { 10, 20 };
scores.AddRange(new int[] { 30, 40, 50 });

// Result: [10, 20, 30, 40, 50]

Accessing Items

List<string> planets = new List<string>() { "Earth", "Mars", "Venus" };

Console.WriteLine(planets[0]);   // Earth
Console.WriteLine(planets[2]);   // Venus

// Update a value:
planets[1] = "Jupiter";
Console.WriteLine(planets[1]);   // Jupiter

// Count of items:
Console.WriteLine(planets.Count); // 3

Removing Items

List<string> colors = new List<string>() { "Red", "Green", "Blue", "Red" };

colors.Remove("Red");       // removes FIRST "Red" only
// Result: [Green, Blue, Red]

colors.RemoveAt(1);         // removes item at index 1
// Result: [Green, Red]

colors.RemoveAll(c => c == "Red");  // removes ALL matching items
// Result: [Green]

Searching a List

List<int> nums = new List<int>() { 5, 12, 7, 22, 9 };

Console.WriteLine(nums.Contains(7));     // True
Console.WriteLine(nums.Contains(100));   // False

Console.WriteLine(nums.IndexOf(22));     // 3
Console.WriteLine(nums.LastIndexOf(5));  // 0

// Find — returns first match:
int found = nums.Find(n => n > 10);
Console.WriteLine(found);               // 12

// FindAll — returns all matches:
List<int> big = nums.FindAll(n => n > 8);
// big = [12, 22, 9]

Sorting a List

List<int> values = new List<int>() { 3, 1, 4, 1, 5, 9, 2 };
values.Sort();
// [1, 1, 2, 3, 4, 5, 9]

values.Reverse();
// [9, 5, 4, 3, 2, 1, 1]

List<string> words = new List<string>() { "Banana", "Apple", "Cherry" };
words.Sort();
// [Apple, Banana, Cherry]

Looping Through a List

List<string> animals = new List<string>() { "Cat", "Dog", "Rabbit" };

// foreach (most common):
foreach (string animal in animals)
{
    Console.WriteLine(animal);
}

// for loop with index:
for (int i = 0; i < animals.Count; i++)
{
    Console.WriteLine(i + ": " + animals[i]);
}

// ForEach method with lambda:
animals.ForEach(a => Console.WriteLine(a));

Converting Between List and Array

// Array to List:
string[] arr = { "A", "B", "C" };
List<string> list = new List<string>(arr);

// List to Array:
string[] back = list.ToArray();

// List to another List:
List<string> copy = new List<string>(list);

Real-World Example: Student Grades

using System;
using System.Collections.Generic;

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

grades.Add(88);
grades.Add(72);
grades.Add(95);
grades.Add(60);
grades.Add(83);

grades.Sort();

int lowest  = grades[0];
int highest = grades[grades.Count - 1];
double avg  = 0;

foreach (int g in grades) avg += g;
avg /= grades.Count;

Console.WriteLine("Lowest:  " + lowest);   // 60
Console.WriteLine("Highest: " + highest);  // 95
Console.WriteLine("Average: " + avg);      // 79.6

List of Objects

class Student
{
    public string Name;
    public int Score;
}

List<Student> students = new List<Student>();

students.Add(new Student { Name = "Alice", Score = 90 });
students.Add(new Student { Name = "Bob",   Score = 75 });
students.Add(new Student { Name = "Carol", Score = 88 });

foreach (Student s in students)
{
    Console.WriteLine(s.Name + ": " + s.Score);
}
// Output:
// Alice: 90
// Bob: 75
// Carol: 88

Quick Method Reference

┌─────────────────────────┬────────────────────────────────────┐
│ Method/Property         │ What It Does                       │
├─────────────────────────┼────────────────────────────────────┤
│ Add(item)               │ Append to end                      │
│ AddRange(collection)    │ Append multiple items              │
│ Insert(index, item)     │ Add at specific position           │
│ Remove(item)            │ Remove first match                 │
│ RemoveAt(index)         │ Remove by index                    │
│ RemoveAll(predicate)    │ Remove all that match condition    │
│ Contains(item)          │ Check existence                    │
│ IndexOf(item)           │ Find index of item                 │
│ Find(predicate)         │ Return first match                 │
│ FindAll(predicate)      │ Return all matches as List         │
│ Sort()                  │ Sort in place                      │
│ Reverse()               │ Reverse order                      │
│ Clear()                 │ Remove all items                   │
│ Count                   │ Number of items                    │
│ ToArray()               │ Convert to array                   │
│ ForEach(action)         │ Run action on each item            │
└─────────────────────────┴────────────────────────────────────┘

List<T> is the most commonly used collection in C# programs. It combines the flexibility of dynamic sizing with the safety of strict typing. For almost every situation where you need a collection of items, List<T> is the right first choice.

Leave a Comment

Your email address will not be published. Required fields are marked *