List patterns help you check and work with lists in a simple and clear way. They make your code easier to read and understand.
List patterns in C Sharp (C#)
public class ListPatternExample { public static void CheckListPattern(List<int> numbers) { switch (numbers) { case []: Console.WriteLine("The list is empty."); break; case [var first]: Console.WriteLine($"The list has one element: {first}"); break; case [var first, var second]: Console.WriteLine($"The list has two elements: {first} and {second}"); break; case [var first, .. var rest]: Console.WriteLine($"The list starts with {first} and has {rest.Count} more elements."); break; default: Console.WriteLine("The list has some elements."); break; } } }
List patterns use square brackets [] to match list shapes.
Use var to capture elements from the list.
[].List<int> emptyList = new(); CheckListPattern(emptyList);
[var first].List<int> singleItemList = new() { 5 }; CheckListPattern(singleItemList);
[var first, var second].List<int> twoItemsList = new() { 3, 7 }; CheckListPattern(twoItemsList);
[var first, .. var rest].List<int> manyItemsList = new() { 1, 2, 3, 4 }; CheckListPattern(manyItemsList);
This program creates four lists with different numbers of elements. It then uses list patterns to check each list and print a message describing its shape.
using System; using System.Collections.Generic; public class ListPatternExample { public static void CheckListPattern(List<int> numbers) { switch (numbers) { case []: Console.WriteLine("The list is empty."); break; case [var first]: Console.WriteLine($"The list has one element: {first}"); break; case [var first, var second]: Console.WriteLine($"The list has two elements: {first} and {second}"); break; case [var first, .. var rest]: Console.WriteLine($"The list starts with {first} and has {rest.Count} more elements."); break; default: Console.WriteLine("The list has some elements."); break; } } public static void Main() { List<int> emptyList = new(); List<int> singleItemList = new() { 5 }; List<int> twoItemsList = new() { 3, 7 }; List<int> manyItemsList = new() { 1, 2, 3, 4 }; Console.WriteLine("Before checking patterns:"); Console.WriteLine("emptyList: []"); Console.WriteLine("singleItemList: [5]"); Console.WriteLine("twoItemsList: [3, 7]"); Console.WriteLine("manyItemsList: [1, 2, 3, 4]"); Console.WriteLine("\nChecking patterns:"); CheckListPattern(emptyList); CheckListPattern(singleItemList); CheckListPattern(twoItemsList); CheckListPattern(manyItemsList); } }
Time complexity depends on the pattern and list size, but matching is generally fast for small patterns.
Space complexity is minimal since no extra storage is needed for matching.
A common mistake is forgetting the .. operator to capture the rest of the list.
Use list patterns when you want clear and readable code to check list shapes instead of manual index checks.
List patterns let you match lists by their shape using simple syntax.
They make your code easier to read and safer by handling different list cases clearly.
Use [] for empty, [var x] for one element, and [var x, .. var rest] for more elements.
Practice
[] match in C#?Solution
Step 1: Understand the empty list pattern
The pattern[]is used to match lists that have no elements at all.Step 2: Compare with other list patterns
Patterns like[var x]match one element, and[var x, .. var rest]match lists with multiple elements, so they don't match empty lists.Final Answer:
An empty list with no elements -> Option AQuick Check:
Empty list = [] pattern [OK]
- Confusing [] with single element pattern
- Thinking [] matches any list
- Assuming [] matches lists with elements
Solution
Step 1: Identify the pattern for one element
The pattern[var x]matches a list with exactly one element, binding it tox.Step 2: Understand other patterns
[var x, .. var rest]matches lists with at least one element plus the rest,[.. var rest]matches any list, and[]matches empty lists.Final Answer:
[var x] -> Option BQuick Check:
One element list = [var x] [OK]
- Using [var x, .. var rest] for single element
- Using [] for single element list
- Confusing .. var rest with single element
var list = new List<int> { 5, 10, 15 };
switch (list)
{
case []:
Console.WriteLine("Empty");
break;
case [var x]:
Console.WriteLine($"One element: {x}");
break;
case [var x, .. var rest]:
Console.WriteLine($"First: {x}, Rest count: {rest.Count}");
break;
}Solution
Step 1: Analyze the list contents
The list has three elements: 5, 10, and 15.Step 2: Match the list pattern cases
The first case matches empty list, which is false. The second case matches exactly one element, which is false. The third case matches a list with at least one element:[var x, .. var rest]. Here,xis 5, andrestcontains 10 and 15, so count is 2.Final Answer:
First: 5, Rest count: 2 -> Option DQuick Check:
List with 3 elements matches [x, ..rest] pattern [OK]
- Choosing empty or one element case incorrectly
- Miscounting rest elements
- Ignoring pattern order in switch
var numbers = new List<int> { 1, 2, 3 };
if (numbers is [var first, var second])
{
Console.WriteLine($"First: {first}, Second: {second}");
}Solution
Step 1: Understand the pattern [var first, var second]
This pattern matches lists with exactly two elements, binding them tofirstandsecond.Step 2: Check the list size
The list has three elements: 1, 2, and 3, so it does not match the pattern requiring exactly two elements.Final Answer:
The pattern [var first, var second] requires exactly two elements, but list has three -> Option CQuick Check:
Pattern length must match list length exactly [OK]
- Assuming pattern matches partial list
- Thinking variable names cause error
- Ignoring list size in pattern matching
Solution
Step 1: Understand the requirement
The list must start with 1, then have a second element, and then zero or more elements after that (at least two elements total).Step 2: Analyze each pattern
[1, var second, .. var rest]:[1, var second, .. var rest]matches a list starting with 1, then a second element, then the rest (zero or more). This fits the requirement.
[var first, 1, .. var rest]:[var first, 1, .. var rest]matches lists where the second element is 1, not the first.
[1, .. var rest]:[1, .. var rest]matches lists starting with 1 but allows zero or more elements after, so it matches lists with only one element too.
[.. var rest, 1]:[.. var rest, 1]matches lists ending with 1, not starting.Final Answer:
[1, var second, .. var rest] -> Option AQuick Check:
Start with 1 and at least two elements = [1, var second, .. rest] [OK]
- Confusing element positions in pattern
- Using patterns that allow only one element
- Matching end of list instead of start
Ready to prove it?
Pass the test and this pattern moves unknown
