Skip to content

CSharp Collections List Basics

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Collections: List<T> Basics

This lesson introduces the generic List<T> collection in C#.

Related wiki pages:

  • Generics intro: CSharp-Generics-Intro.md
  • Libraries and collections: CSharpBible-Libraries.md

Official docs:


1. Creating and populating a list

using System;
using System.Collections.Generic;

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

fruits.Add("apple");
fruits.Add("banana");
fruits.Add("orange");
fruits.Add("grape");

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Notes:

  • List<string> is a list of strings.
  • Add appends an item to the end of the list.

2. Iterating with foreach

var fruits = new List<string> { "apple", "banana", "orange" };

foreach (string fruit in fruits)
{
    Console.WriteLine("Fruit: " + fruit);
}

For more about foreach, see Lesson14.12.2025.md (to be renamed to a foreach-specific lesson).


3. Removing items

var fruits = new List<string> { "apple", "banana", "orange" };

fruits.Remove("apple");

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit); // banana, orange
}

Remove deletes the first matching element.


4. Accessing by index

var fruits = new List<string> { "apple", "banana", "orange" };

Console.WriteLine(fruits[0]);               // apple
Console.WriteLine(fruits[fruits.Count - 1]); // orange

5. Lists of other types

var numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (int n in numbers)
{
    Console.WriteLine(n);
}

List<T> works with any type T.


6. Useful methods

var fruits = new List<string> { "banana", "apple", "orange" };

fruits.Sort();                // sorts in-place (alphabetically)
bool hasBanana = fruits.Contains("banana");

See the official docs and CSharp-LINQ-Where-OrderBy.md for more powerful querying and ordering options.

Clone this wiki locally