0
0
C Sharp (C#)programming~5 mins

List patterns in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a list pattern in C#?
A list pattern in C# is a way to match elements inside a list or array by their order and values. It lets you check if a list has specific elements in a certain sequence.
Click to reveal answer
beginner
How do you match the first two elements of a list using list patterns?
You write a pattern like [var first, var second, ..]. This matches a list where the first element is stored in first, the second in second, and .. means any remaining elements.
Click to reveal answer
beginner
What does the .. symbol mean in a list pattern?
The .. symbol means 'match the rest of the list'. It allows the pattern to match lists longer than the elements explicitly listed.
Click to reveal answer
intermediate
Can list patterns be used to check for an exact list length?
Yes. If you write a pattern without .., like [1, 2, 3], it matches only lists with exactly three elements: 1, 2, and 3 in order.
Click to reveal answer
intermediate
Give an example of using list patterns in a switch expression.
Example:<br>
return list switch {
  [1, 2, 3] => "Exact match",
  [1, 2, ..] => "Starts with 1, 2",
  _ => "Other"
};
This checks the list and returns a string based on the pattern matched.
Click to reveal answer
What does the list pattern [var x, var y, ..] match?
AA list with exactly three elements
BA list with exactly two elements
CA list with no elements
DA list with at least two elements, capturing the first two
Which list pattern matches only a list with exactly three elements 1, 2, and 3?
A[1, 2, 3]
B[1, 2, ..]
C[.., 1, 2, 3]
D[1, .., 3]
In C# list patterns, what does the underscore (_) pattern mean?
AMatch a list with one element
BMatch an empty list only
CMatch any list
DMatch a list with exactly two elements
Which of these is a valid list pattern in C#?
A{var a, var b, var c}
B[var a, var b, var c]
C(var a, var b, var c)
D<var a, var b, var c>
What happens if you use [1, 2, ..] to match the list [1, 2]?
AIt matches successfully
BIt does not match
CIt throws an error
DIt matches only if the list has more than two elements
Explain how list patterns work in C# and how you can use them to check list contents.
Think about how you check items in a list one by one.
You got /4 concepts.
    Describe a scenario where list patterns can simplify your code compared to traditional if-else checks.
    Imagine you want to do different things based on the first few items in a list.
    You got /4 concepts.