-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Collections List Basics
Joe Care edited this page Dec 22, 2025
·
1 revision
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:
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. -
Addappends an item to the end of the list.
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).
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.
var fruits = new List<string> { "apple", "banana", "orange" };
Console.WriteLine(fruits[0]); // apple
Console.WriteLine(fruits[fruits.Count - 1]); // orangevar numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int n in numbers)
{
Console.WriteLine(n);
}List<T> works with any type T.
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.