In C# 11, a game-changing feature was introduced – List Patterns. These patterns enable you to effortlessly match an array or a list with a sequence of elements. Let's explore the three distinct list pattern matching techniques.
1. Discard Pattern
The Discard Pattern is useful when you know the length of the sequence. For instance, matching an array of five integers against another array with the same values.
var ids = new[] { 1, 2, 3, 4, 5 };
if (ids is [1, 2, 3, 4, 5])
{
Console. WriteLine("Its matched");
}
To match regardless of the values, you can use the underscore (_).
if (ids is [_, _, _, _, _])
{
Console. WriteLine("Its matched");
}
2. Range Pattern
When you're unsure about the sequence length, the Range Pattern comes into play. Use two dots (..) to specify any number of elements. For instance.
if (ids is [1, ..])
{
Console. WriteLine("Its matched");
}
Combining range with the discard pattern.
if (ids is [1, _, 3, ..])
{
Console. WriteLine("Its matched");
}
3. Var Pattern
The Var Pattern allows you to declare variables and assign matched elements. These variables are accessible in the same scope.
if (ids is [var one, var two, ..])
{
Console.WriteLine($"{one}, {two}");
}
These C# List patterns empower you to write more concise and expressive code, enhancing your ability to work with sequences effectively. Dive into the versatility of list patterns and take your C# coding to the next level!
Why do you want to stop here, go ahead with our similar stuff Collection expressions in C# 12.0