๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

C# List Patterns

A list pattern matches the elements of an array or list in order. It can fix some positions and let a slice cover the rest.

Exact list matches

The first pattern lists every element of the array. The shorter pattern fails, because the lengths differ.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 1, 2, 3 };
        Console.WriteLine(data is [1, 2, 3]);
        Console.WriteLine(data is [1, 2]);
    }
}

Slice patterns

Each pattern anchors one or both ends and lets the slice cover the middle. All three tests pass for the same array.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 1, 2, 3 };
        Console.WriteLine(data is [1, ..]);
        Console.WriteLine(data is [.., 3]);
        Console.WriteLine(data is [1, .., 3]);
    }
}

Capturing elements and the rest

The first element binds to first. The slice binds the remaining elements to rest.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 1, 2, 3 };
        if (data is [var first, .. var rest])
        {
            Console.WriteLine(first);
            Console.WriteLine(rest.Length);
        }
    }
}

Example

using System;

class Program
{
    static string Describe(int[] data)
    {
        return data switch
        {
            [100, ..] => "Perfect start",
            [.., 0] => "Ends at zero",
            _ => "Other",
        };
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Describe(new int[] { 100, 90, 80 }));
        Console.WriteLine(Describe(new int[] { 5, 0 }));
        Console.WriteLine(Describe(new int[] { 1, 2 }));
    }
}

Key points

  • A list pattern sits in square brackets and matches element by element.
  • Without a slice, the pattern needs the exact length.
  • The slice pattern .. matches any number of elements, including zero.
  • A slice at the start anchors the end of the sequence.
  • A slice in the middle anchors both ends at once.
  • A var pattern inside a list captures one element.
  • A slice with var captures the remaining elements as a new sequence.

In this example, the Describe method switches over an array with list patterns. The first array starts with 100, so the first arm matches. The second array ends with 0, and the third array falls through to the discard arm.

Note

List patterns work in is tests, switch arms, and switch expressions.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which array matches the pattern [1, .., 3]?