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.
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.
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]);
}
}2
appleCount gives the number of items, and fruits[0] accesses the first item by index.
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));
}
}1, 3, 5Sort() 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;`.
