Lists

View saved

Create and add items

List<T> lives in System.Collections.Generic and is imported by default in modern templates.

var names = new List<string>();
names.Add("Ada");
names.Add("Lin");
Console.WriteLine(names.Count);

Initialize with values

Collection expressions or initializers keep setup short.

var nums = new List<int> { 1, 2, 3 };
nums.Remove(2);
Console.WriteLine(string.Join(",", nums));

Find and check

Useful helpers cover common searches.

Console.WriteLine(names.Contains("Ada"));
Console.WriteLine(names.IndexOf("Lin"));

List habits

  • Prefer List<T> over arrays when length changes
  • Choose a meaningful element type instead of object
  • Clear intent with Clear, Insert, and RemoveAt
  • Later, LINQ queries work especially well on lists

Comments

One comment per signed-in account. Comments are saved with this page’s URL.