csharp / intermediate
Snippet
Matching Sequence Structures with List Patterns
List patterns allow you to match arrays or lists against a specific sequence of elements. Using the discard (_) or the range operator (..) allows for flexible validation of data structures based on their positional content.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
string[] tags = { "v1", "beta", "prod" };if (tags is ["v1", var status, ..]){Console.WriteLine($"Current status: {status}");}// Matching empty or specific lengthsbool isEmpty = tags is [];bool hasThree = tags is [_, _, _];
Breakdown
1
tags is ["v1", var status, ..]
Matches if the array starts with 'v1', captures the second element, and ignores the rest.
2
tags is []
Checks if the collection is empty using pattern matching syntax.