Edit

Common collection types

Tip

This article is part of the Fundamentals section for developers who already know at least one programming language and are learning C#. If you're new to programming, start with the Get started tutorials first. For more information about collections, see Collections in the language reference. For more information about arrays, see The array reference type in the language reference. For more information about collection expressions, see Collection expressions (Collection literals) in the language reference.

Coming from another language? C# arrays are fixed-size ordered collections, like arrays in Java or C++. List<T> is the everyday growable sequence, like Java's ArrayList, JavaScript's arrays, or Python's lists. Dictionary<TKey,TValue> stores values by key, like maps or dictionaries in many languages.

A collection is an object that stores multiple related values. Each value in a collection is an element. Choose an array when the set is fixed, such as the status names your work-item tracker always uses. Choose a List<T> when items come and go, such as a backlog that gains new work and drops completed items. Choose a Dictionary<TKey,TValue> when you look up values by a key, such as finding a work item by ID or a setting by name. The next section turns those examples into a quick decision model.

Choose a collection shape

Choose the collection that matches how your code uses the data. A sequence stores elements in order so you can reach them by position. Use an array, which is represented by Array, when you know the number of positions the sequence needs. An array's length can't change after you create it, but you can replace the element stored at an existing position. Use List<T> when you need a sequence that can add or remove elements. A dictionary stores values that you reach by key instead of by position. Use Dictionary<TKey,TValue> when each element has a lookup key, such as a name, ID, or code. The examples use a collection expression, which creates a collection from expressions between square brackets. The Create collections with collection expressions section explains that syntax in more detail.

string[] sprintPlan = ["design", "code", "test"];
List<string> backlog = ["design", "code"];
Dictionary<string, int> priorities = new()
{
    ["docs"] = 2,
    ["tests"] = 1
};

backlog.Add("test");

Console.WriteLine($"Array: {string.Join(", ", sprintPlan)}");
Console.WriteLine($"List count: {backlog.Count}");
Console.WriteLine($"Priority for docs: {priorities["docs"]}");
// This example produces the following output:
//
//    Array: design, code, test
//    List count: 3
//    Priority for docs: 2
//

List<T> and Dictionary<TKey,TValue> are generic types. A generic type uses a type argument, such as string or int, to say what kind of values it stores. Generics let you reuse the same collection shape, such as a list or dictionary, with different element types, such as string, int, or a custom type. They also provide type safety: the compiler guarantees every element is the declared type, so you don't need casts and can't accidentally store the wrong type. For more information about generic types, see Generic types and methods in the fundamentals.

Store fixed-size data in arrays

An array is an ordered collection with a fixed length. You access an array element by its index, which is its zero-based position in the array. Index 0 is the first element, index 1 is the second element, and so on.

string[] stages = ["design", "code", "test", "review"];

Console.WriteLine($"First: {stages[0]}");
Console.WriteLine($"test index: {Array.IndexOf(stages, "test")}");
// This example produces the following output:
//
//    First: design
//    test index: 2
//

Use foreach when you want to read every element in order. Use an index when the position matters, such as when you need the first element, the last element, or the position returned by Array.IndexOf.

The length of an array is fixed, but the elements in that array can change. Assign a new value to an existing index when the position stays the same but the stored value needs an update:

string[] stages = ["design", "code", "test"];

stages[0] = "plan";

Console.WriteLine(string.Join(", ", stages));
Console.WriteLine($"Length: {stages.Length}");
// This example produces the following output:
//
//    plan, code, test
//    Length: 3
//

Grow and shrink a sequence with List<T>

A List<T> stores elements in order and can grow or shrink as your program runs. Use Add to append an element, Remove to remove a matching element, Contains to test whether an element exists, and IndexOf to find an element's position. Use the list indexer to replace the value at an existing position.

List<string> workItems = ["design", "code", "test"];

workItems.Add("review");
workItems.Remove("code");
workItems[1] = "verify";

Console.WriteLine(string.Join(", ", workItems));
Console.WriteLine($"Has review: {workItems.Contains("review")}");
Console.WriteLine($"Index of verify: {workItems.IndexOf("verify")}");
// This example produces the following output:
//
//    design, verify, review
//    Has review: True
//    Index of verify: 1
//

A List<T> keeps the remaining elements in order when you add or remove items. When you remove an element, later elements move to lower indexes.

Use Insert to add one element at a specific position, InsertRange to add several elements at a position, and RemoveAt to remove an element by index:

List<string> workItems = ["design", "test"];

workItems.Insert(1, "code");
Console.WriteLine($"Insert middle: {string.Join(", ", workItems)}");

workItems.Insert(0, "plan");
Console.WriteLine($"Insert front: {string.Join(", ", workItems)}");

workItems.InsertRange(workItems.Count, ["review", "deploy"]);
Console.WriteLine($"Insert range at end: {string.Join(", ", workItems)}");

workItems.RemoveAt(workItems.Count - 1);
Console.WriteLine($"Remove end: {string.Join(", ", workItems)}");

workItems.RemoveAt(2);
Console.WriteLine($"Remove middle: {string.Join(", ", workItems)}");

workItems.RemoveAt(0);
Console.WriteLine($"Remove front: {string.Join(", ", workItems)}");
// This example produces the following output:
//
//    Insert middle: design, code, test
//    Insert front: plan, design, code, test
//    Insert range at end: plan, design, code, test, review, deploy
//    Remove end: plan, design, code, test, review
//    Remove middle: plan, design, test, review
//    Remove front: design, test, review
//

Adding or removing at the end of a List<T> is fast. Adding with Add is an O(1) operation on average, and removing the last element with RemoveAt is O(1). Inserting or removing at the front or middle is O(n) because every later element shifts to a new index. If your code frequently inserts or removes at the front, a List<T> might be the wrong collection shape.

Tip

Big-O notation describes how the work grows as the collection size, n, grows. O(1), pronounced "order one," means the operation takes about the same amount of work no matter how many elements the collection contains. O(n), pronounced "order n," means the work grows roughly in proportion to the number of elements in the collection.

Associate a value by key with Dictionary<TKey,TValue>

A Dictionary<TKey,TValue> stores key/value pairs. A key/value pair is one key and the value associated with that key; .NET represents one pair with KeyValuePair<TKey,TValue>. Use the dictionary indexer to add or update a value by key, and use TryGetValue when the key might not exist.

Dictionary<string, int> priorities = new()
{
    ["docs"] = 2,
    ["tests"] = 1
};

priorities["review"] = 3;
priorities.Remove("review");

if (priorities.TryGetValue("docs", out int docsPriority))
{
    Console.WriteLine($"docs priority: {docsPriority}");
}
else
{
    Console.WriteLine("docs missing");
}

if (priorities.TryGetValue("deploy", out int deployPriority))
{
    Console.WriteLine($"deploy priority: {deployPriority}");
}
else
{
    Console.WriteLine("deploy missing");
}

Console.WriteLine($"count: {priorities.Count}");
// This example produces the following output:
//
//    docs priority: 2
//    deploy missing
//    count: 2
//

An indexer lets you use bracket syntax to access a value from an object. The dictionary indexer is useful when the key must exist or when you're assigning a value. TryGetValue checks whether a key exists and gives you the value when it does. For more information about the indexer operator, see Member access operators in the language reference.

You can also change the value associated with a key that already exists. Assign through the indexer to add a key or replace the value for an existing key. If the replacement depends on the current value, read the value first, then assign the new value:

Dictionary<string, int> priorities = new()
{
    ["docs"] = 2,
    ["tests"] = 1
};

priorities["docs"] = 1;

if (priorities.TryGetValue("tests", out int testsPriority))
{
    priorities["tests"] = testsPriority + 1;
}

priorities["deploy"] = 3;

Console.WriteLine($"docs priority: {priorities["docs"]}");
Console.WriteLine($"tests priority: {priorities["tests"]}");
Console.WriteLine($"deploy priority: {priorities["deploy"]}");
// This example produces the following output:
//
//    docs priority: 1
//    tests priority: 2
//    deploy priority: 3
//

Create collections with collection expressions

A collection expression creates a collection from expressions between square brackets. Beginning with C# 12, collection expressions can create arrays, lists, and other collection types. A spread element copies the elements from another collection into the new collection.

string[] planned = ["design", "code"];
// The spread element .. planned copies each element from planned.
string[] upcoming = [.. planned, "test"];
List<string> blocked = ["docs"];

Console.WriteLine($"Upcoming: {string.Join(", ", upcoming)}");
Console.WriteLine($"Blocked: {string.Join(", ", blocked)}");
// This example produces the following output:
//
//    Upcoming: design, code, test
//    Blocked: docs
//

Collection expressions keep initialization concise. A collection expression has no type of its own. The compiler converts the expression into the collection shape the context calls for. The receiving variable or parameter can turn it into an array, a List<T>, or other supported collection type.

Read from positions with indexes and ranges

Indexes answer "which single element?" Ranges answer "which contiguous slice?" Use indexes when your code needs one element and ranges when the subsection is part of the data you're working with. Arrays and List<T> support both indexes and ranges.

An Index can count from the start or from the end of a sequence. Use the number directly to count from the start: phases[0] reads the first element, and phases[1] reads the second element. Use ^ to count from the end: phases[^1] reads the last element, and phases[^2] reads the next-to-last element.

An Range selects a slice with .. (two dots). The range operator isn't the same as the spread element you saw earlier in collection expressions, even though both use dots. Use a range a..b when you want elements from index a up to, but not including, index b. The expression phases[1..3] creates a new array that contains the elements at index 1 and index 2.

You can omit one or both range indexes. Omit the start index when the slice starts at the beginning, as in phases[..2] for the first two elements. Omit the end index when the slice continues through the last element, as in phases[2..] for the elements from index 2 to the end. Omit both indexes when you want a copy of the whole array, as in phases[..]. A range can mix index kinds. The expression phases[1..^1] combines a from-start index and a from-end index to return the middle elements, code and test.

string[] phases = ["design", "code", "test", "deploy"];
List<string> checklist = ["design", "test", "review"];

Console.WriteLine($"Last: {phases[^1]}");
Console.WriteLine($"Middle: {string.Join(", ", phases[1..3])}");
Console.WriteLine($"Last two: {string.Join(", ", phases[^2..])}");
Console.WriteLine($"Without ends: {string.Join(", ", phases[1..^1])}");
Console.WriteLine($"First two: {string.Join(", ", phases[..2])}");
Console.WriteLine($"From third: {string.Join(", ", phases[2..])}");
Console.WriteLine($"All phases: {string.Join(", ", phases[..])}");
Console.WriteLine($"List last: {checklist[^1]}");
Console.WriteLine($"List first two: {string.Join(", ", checklist[0..2])}");
// This example produces the following output:
//
//    Last: deploy
//    Middle: code, test
//    Last two: test, deploy
//    Without ends: code, test
//    First two: design, code
//    From third: test, deploy
//    All phases: design, code, test, deploy
//    List last: review
//    List first two: design, test
//

For more information about indexes and ranges, see Explore ranges of data using indices and ranges in the tutorials.

See also