With the release of C#10 and C#11 pattern matching was further enhanced to include the list pattern matching, enabling developers to deconstruct and analyze the array and collection.
Pattern matching in C# allows you to inspect the structure and values of an object cleanly and expressively.
List pattern matching allows the elements of a list or array to be matched declaratively. It allows you to track individual items, also the order of the collection, such as length and size in specific locations.
This is extremely useful when working with operations that need an element-based evaluation of collections, such as checking if a list starts with certain values or has a specific number of elements.
The syntax for list pattern matching uses square brackets [] to specify the pattern to match the collection elements. Here are some common uses:
The following is an example of list pattern matching:
To check if a list is empty, you can use a simple pattern:
csharpint[] numbers = new int[] { }; if (numbers is []) { Console.WriteLine("The list is empty."); }
Here, you can match a list of a specific length by specifying placeholders: The pattern [_, _, _] matches any array with exactly three elements, regardless of the values.
csharpint[] numbers = new int[] { 1, 2, 3 }; if (numbers is [_, _, _]) { Console.WriteLine("The list contains exactly 3 elements."); }
In this example, the pattern [1, ..] checks if the first element is 1, while .. ignores the rest of the elements, and The pattern [.., 3] matches lists that end with 3.
csharpint[] numbers = new int[] { 1, 2, 3 }; if (numbers is [.., 3]) { Console.WriteLine("The list ends with 3."); } if (numbers is [1, .., 3]) { Console.WriteLine("The list starts with 1 and ends with 3."); } //We check both at one time using this syntax if (numbers is [1, .., 3]) { Console.WriteLine("The list starts with 1 and ends with 3."); }
In this example, the first and second elements are deconstructed and then stored in variables first and second.
csharpint[] numbers = new int[] { 1, 2, 3 }; if (numbers is [var first, var second, ..]) { Console.WriteLine($"The first two elements are {first} and {second}."); }
List pattern matching can also be combined with other types of patterns, such as type patterns and relation patterns.
In this example, combining it with conditional checks for more complex scenarios:
int[] numbers = new int[] { 1, 2, 3 }; if (numbers is [>= 1, <= 2, ..]) { Console.WriteLine("First element is >= 1 and second is <= 2."); }
Copyrights © 2024 letsupdateskills All rights reserved