In this blog post, we will explore few hidden gems in list patterns , which was introduced with C# 11.
List Pattern allows us to check patterns in arrays or list.
Assign Variable
You can assign variables using pattern, provided the pattern matches. For example,
var arr = new [] {1,2,3,4,5};
if(arr is [_,2,var third,..] match)
{
Console.WriteLine($"Matched with {match.Count()} with third element {third}");
}
The above code would match the pattern and would also assign the variable third
with the third element in the array, which is incidently is an integer with value 3.
Match Constraints
You could also use the list patterns to match constraints. For example,
if(arr is [_,>=2,_,4 or 5,..] match)
{
}
The above code checks if the 2nd element is less than or equal to 2 and the 4th element is either 4 or 5.
There are other usages of list pattern, but I found the above two quite useful, even though rather underused.