Skip to content
csharpintermediate

C# LINQ

LINQ queries and method syntax

7 questions

By EZ4Code Team

1. What are the two main syntaxes of LINQ?

Query expression (SQL-like) and method syntax (extension methods + lambdas)
Only method syntax
Only query expression
SQL and JSON
Explanation: LINQ supports query expressions (from ... select) and method syntax (.Where().Select()); they are interchangeable, but method syntax is more flexible.

2. What does the following code output? var nums = new List<int>{1,2,3,4}; var evens = nums.Where(n => n % 2 == 0).ToList(); Console.WriteLine(evens.Count);

var nums = new List<int>{1,2,3,4};
var evens = nums.Where(n => n % 2 == 0).ToList();
Console.WriteLine(evens.Count);
2
4
1
Error
Explanation: Where filters even numbers (2,4); after ToList, Count is 2.

3. What concept does the Select method correspond to?

Projection (maps each element to a new form)
Filtering
Sorting
Grouping
Explanation: Select is a projection operation that applies a transformation function to each element, similar to map; Where is filtering.

4. What is the characteristic of deferred execution?

The query executes when enumerated, not when defined
The query executes immediately
The query does not execute
The query executes at compile time
Explanation: Where/Select etc. are deferred; they are not actually evaluated until ToList/Count/foreach triggers enumeration, allowing query chaining.

5. What does GroupBy do?

Groups by key, returning a sequence of IGrouping<TKey,TElement>
Sorting
Deduplication
Projection
Explanation: GroupBy(keySelector) groups by the specified key; each group is an IGrouping<TKey, TElement> and can be further aggregated.

6. What is the difference between First and FirstOrDefault?

First throws when there is no element; FirstOrDefault returns the default value
They are exactly the same
First returns the default value
FirstOrDefault throws
Explanation: First returns the first element and throws InvalidOperationException if there is none; FirstOrDefault returns default(T) (null for reference types).

7. What is the relationship between OrderBy and ThenBy?

OrderBy is the primary sort; ThenBy adds a secondary sort after OrderBy
They are the same
ThenBy replaces OrderBy
OrderBy comes after ThenBy
Explanation: OrderBy creates the primary sort (IOrderedEnumerable); ThenBy/ThenByDescending add secondary sort keys on top of it.

More csharp Quizzes