C# 11 list pattern examples

Beginning with C# 11, we can use list patterns to match elements of a list or array.

Some examples of different types of patterns we can use include …

Constant and Relational Patterns

Discard Patterns

The Discard pattern assumes that you know the length of the sequence and match one or more elements from the sequence.

Range Patterns

If you don’t know the length of the sequence, you can use the range pattern. In the range pattern, you can use the two dots .. to specify any number of elements.

Note that you can use the two dots once in the sequence.

Var Patterns

The var pattern allows you to declare a variable and assign it the value of the matched item. This variable will be available in the same scope where it was declared.

What do you think?
Do you have uses cases for any of these list patterns?