Checking list contents with if statements is verbose. C# 11 list patterns make it clean.
Traditional Way:
if (numbers.Count >= 3 && numbers[0] == 1 && numbers[2] == 3)
{
// Do something
}
List Pattern:
if (numbers is [1, _, 3, ..])
{
// Matches list starting with 1, any value, then 3, then anything
}
// _ = any single element
// .. = zero or more elements
More Examples:
// Exactly 3 elements
if (list is [var first, var second, var third]) { }
// At least 2 elements
if (list is [var first, var second, ..]) { }
// Starts with 1, ends with 5
if (list is [1, .., 5]) { }
// Empty list
if (list is []) { }
// Single element
if (list is [var only]) { }
// Two elements
if (list is [var first, var second]) { }
In Switch:
var message = numbers switch
{
[] => "Empty",
[var x] => $"Single: {x}",
[var x, var y] => $"Pair: {x}, {y}",
[1, .., 5] => "Starts 1, ends 5",
_ => "Other"
};
Pattern matching for collections!
