Consider the following C# code using LINQ query syntax. What will be printed?
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5 }; var query = from n in numbers where n % 2 == 0 select n * n; foreach (var item in query) { Console.Write(item + " "); } } }
Look at the where clause filtering even numbers, then the select projects squares.
The query filters numbers to only even ones (2 and 4), then selects their squares (4 and 16). So output is "4 16 ".
Given a list of names, which LINQ query syntax correctly selects only those starting with the letter 'J'?
string[] names = { "John", "Alice", "James", "Bob" };Remember the where clause comes before select in query syntax.
Option B correctly uses where to filter names starting with 'J' before selecting them. Option B and C have syntax errors. Option B filters names containing 'J' anywhere, not just starting with 'J'.
Examine the following LINQ query code. What error will it cause when compiled?
int[] nums = {1, 2, 3}; var q = from n in nums where n > 1 select n > 2 ? n : ;
Look carefully at the ternary operator syntax in the select clause.
The ternary operator is incomplete because the 'else' part after ':' is missing, causing a syntax error.
What will be printed by this C# program using LINQ query syntax with ordering?
using System; using System.Linq; class Program { static void Main() { string[] fruits = { "apple", "banana", "cherry", "date" }; var query = from f in fruits orderby f.Length descending, f select f; foreach (var fruit in query) { Console.Write(fruit + " "); } } }
Order by length descending, then alphabetically ascending.
Fruits ordered by length descending: banana(6), cherry(6), apple(5), date(4). For ties (banana, cherry), order alphabetically ascending: banana before cherry.
Given this LINQ query, how many items will the result collection contain?
int[] values = { 2, 4, 6, 8, 10 }; var result = from v in values where v % 4 == 0 select v / 2;
Check which numbers in the array are divisible by 4.
Only 4 and 8 are divisible by 4, so the query selects 2 items (4/2=2 and 8/2=4).