C# ยท Chapter 23 of 46

C# List and Collections

A List<T> is a resizable collection, unlike arrays which have a fixed size. Lists are part of the System.Collections.Generic namespace and are one of the most commonly used collection types in C#.

Lists provide many convenient methods like Add(), Remove(), Contains(), and Sort(), making them easier to work with than plain arrays for dynamic data.

Syntax
List<type> name = new List<type>();
name.Add(value);

Creating and modifying a List

A List<T> is declared with a type in angle brackets, like `List<string> names = new List<string>();`. Use Add() to append items and Remove() to delete a specific value.

Common List methods

Contains() checks if a value exists, Count gives the number of items, Sort() orders the elements, and indexing with [] accesses a specific position, just like arrays.

Example 1 (csharp)
using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    List<string> fruits = new List<string>();
    fruits.Add("apple");
    fruits.Add("banana");
    Console.WriteLine(fruits.Count);
    Console.WriteLine(fruits[0]);
  }
}
Output
2
apple

Count gives the number of items, and fruits[0] accesses the first item by index.

Example 2 (csharp)
using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    List<int> numbers = new List<int> { 5, 3, 1 };
    numbers.Sort();
    Console.WriteLine(string.Join(", ", numbers));
  }
}
Output
1, 3, 5

Sort() reorders the list in ascending order, and string.Join() combines items into a single string.

Key points

  • List<T> is a resizable collection, unlike a fixed-size array.
  • Add() and Remove() modify the list's contents.
  • Count gives the number of elements currently in the list.
  • Lists require `using System.Collections.Generic;`.
๐Ÿ’ก Note: Prefer List<T> over arrays when the number of elements can change during the program's execution.

๐Ÿ“ Quick Quiz

1. What namespace is needed to use List<T>?

2. Which method adds an item to a List?

3. What advantage does a List have over an array?