C#idiomatic C#
collectionscsharp/fundamentals/statements

Language

Common collection types

Store, update, search, and read groups of values by using arrays, lists, dictionaries, collection expressions, indexes, and ranges.

  • page csharp/fundamentals/statements/collections
  • updated 07/15/2026

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 System.Collections.Generic.List when items come and go, such as a backlog that gains new work and drops completed items. Choose a System.Collections.Generic.Dictionary 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 System.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 System.Collections.Generic.List 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 System.Collections.Generic.Dictionary 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.

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csChooseCollection

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

System.Collections.Generic.List and System.Collections.Generic.Dictionary 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.

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csArrays

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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 System.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:

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csArrayElementUpdate

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

Grow and shrink a sequence with List<T>

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

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csListChanges

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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

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

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csListInsertRemove

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

Adding or removing at the end of a System.Collections.Generic.List is fast. Adding with System.Collections.Generic.List.Add is an O(1) operation on average, and removing the last element with System.Collections.Generic.List.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 System.Collections.Generic.List might be the wrong collection shape.

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

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

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csDictionaryLookup

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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. System.Collections.Generic.Dictionary.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:

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csDictionaryUpdates

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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.

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csCollectionExpressions

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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 System.Collections.Generic.List, 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 System.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 System.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.

sample · csharpdocs/csharp/fundamentals/statements/snippets/collections-statements/Program.csIndexesAndRanges

csharp
namespace CollectionStatements;

public static class Program
{
    public static void Main()
    {
        ChooseCollectionExample();
        ArraysExample();
        ArrayElementUpdateExample();
        ListChangesExample();
        ListInsertRemoveExample();
        DictionaryLookupExample();
        DictionaryUpdatesExample();
        CollectionExpressionsExample();
        IndexesAndRangesExample();
    }

    private static void ChooseCollectionExample()
    {
        // <ChooseCollection>
        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
        //
        // </ChooseCollection>
    }

    private static void ArraysExample()
    {
        // <Arrays>
        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
        //
        // </Arrays>
    }

    private static void ArrayElementUpdateExample()
    {
        // <ArrayElementUpdate>
        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
        //
        // </ArrayElementUpdate>
    }

    private static void ListChangesExample()
    {
        // <ListChanges>
        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
        //
        // </ListChanges>
    }

    private static void ListInsertRemoveExample()
    {
        // <ListInsertRemove>
        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
        //
        // </ListInsertRemove>
    }

    private static void DictionaryLookupExample()
    {
        // <DictionaryLookup>
        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
        //
        // </DictionaryLookup>
    }

    private static void DictionaryUpdatesExample()
    {
        // <DictionaryUpdates>
        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
        //
        // </DictionaryUpdates>
    }

    private static void CollectionExpressionsExample()
    {
        // <CollectionExpressions>
        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
        //
        // </CollectionExpressions>
    }

    private static void IndexesAndRangesExample()
    {
        // <IndexesAndRanges>
        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
        //
        // </IndexesAndRanges>
    }
}

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

See also