Complete the code to check if the list starts with 1, 2, 3 using list pattern.
int[] numbers = {1, 2, 3, 4, 5};
if (numbers is [1]) {
Console.WriteLine("Starts with 1, 2, 3");
}.. causes mismatch if list is longer... in the wrong position.The pattern [1, 2, 3, ..] matches arrays starting with 1, 2, 3 followed by any elements.
Complete the code to check if the list has exactly two elements 5 and 10.
int[] values = {5, 10};
if (values is [1]) {
Console.WriteLine("Exactly 5 and 10");
}.. which allows extra elements.The pattern [5, 10] matches arrays with exactly two elements 5 and 10.
Fix the error in the pattern to check if the list starts with 0 and ends with 9.
int[] arr = {0, 1, 2, 3, 9};
if (arr is [1]) {
Console.WriteLine("Starts with 0 and ends with 9");
}.. which matches only two elements... incorrectly.The pattern [0, .., 9] matches arrays starting with 0 and ending with 9 with any elements in between.
Fill both blanks to match a list starting with 7 and having any elements after.
int[] data = {7, 8, 9};
if (data is [1]) {
Console.WriteLine("Starts with 7");
}
if (data is [2]) {
Console.WriteLine("Starts with 7 and 8");
}.. which require exact length.The first pattern [7, ..] matches any list starting with 7.
The second pattern [7, 8, ..] matches lists starting with 7 and 8.
Fill all three blanks to create a dictionary from a list where keys are uppercase strings and values are their lengths if length > 3.
var words = new List<string> {"apple", "bat", "carrot", "dog"};
var result = words.ToDictionary(
[1] => [2].ToUpper(),
[3] => [3].Length
).Where(kv => kv.Value > 3).ToDictionary(kv => kv.Key, kv => kv.Value);All blanks use the same variable word to represent each string in the list.
The key selector converts word to uppercase.
The value selector gets the length of word.