Mastering List Pattern Matching in C# 11 (An In-Depth Guide with Examples)
Mastering List Pattern Matching in C# 11: An In-Depth Guide with Examples
One of the exciting features introduced is list pattern matching, which significantly improves upon the way we can work with collections. To provide some context, list pattern matching in C# 11 is part of a broader move to enhance pattern matching in the language, which was first introduced in C# 7.0.
Let's take a look at a few examples to understand how this feature works:
Example 1: Basic List Pattern Matching
var numbers = new List<int> {1, 2, 3, 4, 5};
if (numbers is {1, 2, _, 4, 5})
{
Console.WriteLine("The third element can be any value.");
}
In this example, the _
is a discard that matches any value. This code prints the message if numbers
starts with 1
and 2, has any value as the third element, and ends with 4 and 5.
Example 2: Length Pattern
var colors = new List<string> {"red", "blue", "green"};
if (colors is ["red", "blue", "green"])
{
Console.WriteLine("The list contains exactly these three colors and in this order.");
}
This example checks if colors
contains exactly "red", "blue", and "green" in this order.
Example 3: Using ..
to Match Remaining Elements
var names = new List<string> {"Alice", "Bob", "Charlie", "David"};
if (names is {"Alice", ..})
{
Console.WriteLine("The list starts with 'Alice'.");
}
In this example, the ..
pattern is used to match any number of remaining elements, thus checking if the list starts
with "Alice".
Example 4: Using var pattern in List Pattern Matching
var mixedList = new List<object> { 1, "two", 3.0 };
if (mixedList is { var integer when integer is int, var text when text is string, var real when real is double })
{
Console.WriteLine($"The first item is integer: {integer}, second item is string: {text}, and the third item is double: {real}.");
}
Here, the var
pattern is used to create new variables of matched elements which can further be constrained with when
clauses.
List pattern matching can be very useful when dealing with collections, improving both readability and functionality of
your code. Note that list pattern matching works with any type that has an accessible Length
or Count
property, and
an accessible indexer ([]
).