Consider the following C# code using LINQ to group numbers by their remainder when divided by 3. What will be printed?
var numbers = new[] {1, 2, 3, 4, 5, 6}; var groups = numbers.GroupBy(n => n % 3).OrderBy(g => g.Key); foreach (var group in groups) { Console.Write($"{group.Key}: "); foreach (var num in group) Console.Write(num + " "); Console.WriteLine(); }
Remember that GroupBy preserves the order of elements within each group.
The GroupBy groups numbers by their remainder when divided by 3. Numbers 3 and 6 have remainder 0, 1 and 4 have remainder 1, and 2 and 5 have remainder 2. The order inside each group is preserved from the original array.
Which of the following best explains the advantage of deferred execution in LINQ?
Think about when the data is actually fetched or processed.
Deferred execution means the query is not run until you iterate over the results. This can save time and memory by avoiding unnecessary work.
Given the following code, what will be printed?
var data = new[] { new[] {1, 2}, new[] {3, 4}, new[] {5} }; var result = data.SelectMany(arr => arr.Where(x => x % 2 == 0)); foreach (var num in result) { Console.Write(num + " "); }
SelectMany flattens collections and Where filters elements.
SelectMany flattens the arrays into one sequence, but only elements that are even (x % 2 == 0) are selected. So only 2 and 4 are printed.
Examine the following code snippet. What error will it cause when run?
var list = new List<int> {1, 2, 3}; var query = list.Select(x => x / (x - 2)); foreach (var val in query) { Console.Write(val + " "); }
Check what happens when x equals 2.
When x is 2, the expression x - 2 is zero, causing a division by zero error during query execution.
Consider this LINQ query that creates a dictionary from a list of strings. How many items will the dictionary contain?
var words = new List<string> {"apple", "banana", "apricot", "blueberry", "avocado"}; var dict = words.GroupBy(w => w[0]) .ToDictionary(g => g.Key, g => g.Count()); Console.WriteLine(dict.Count);
Look at the first letters of each word and count unique letters.
The words start with 'a' (apple, apricot, avocado) and 'b' (banana, blueberry). So there are 2 unique keys: 'a' and 'b'. The dictionary will have 2 items.