C# LINQ Interview Questions
Last updated 2026-11-19
LINQ questions in C# interviews concentrate on two things: behaviour that surprises people (deferred execution, multiple enumeration, closures) and picking the right operator (First versus Single, Select versus SelectMany, Join versus GroupJoin). Output prediction is common because a LINQ query is a recipe, not a result.
The examples use C# 12 on .NET 8, including operators added in recent releases such as Chunk, MaxBy and DistinctBy. Where LINQ meets databases, see Entity Framework Core.
| Namespace | System.Linq |
|---|---|
| Language version | C# 12 on .NET 8 |
| Key idea | Queries are lazy until enumerated |
Operators grouped by what they do
- Filtering and projection: Where, Select, SelectMany, OfType.
- Ordering and paging: OrderBy, ThenBy, Reverse, Skip, Take, Chunk.
- Grouping and joins: GroupBy, ToLookup, Join, GroupJoin, Zip.
- Aggregation: Count, Sum, Min, Max, MaxBy, Aggregate, Any, All.
- Set operations: Distinct, DistinctBy, Union, Intersect, Except.
C# LINQ Interview Questions: questions with worked answers
1 What is deferred execution, and which operators execute immediately?
easyMost LINQ operators build a pipeline and run only when you enumerate it with foreach or call a materialising operator. Where, Select, OrderBy, Skip and Take are deferred. ToList, ToArray, ToDictionary, Count, Sum, First, Any and Aggregate run immediately. Deferred queries see changes made to the source before they are enumerated.
csharpvar list = new List<int> { 1, 2, 3 }; var q = list.Where(x => x > 1); list.Add(4); // source changes before enumeration Console.WriteLine(string.Join(",", q)); // 2,3,4 var snap = list.Where(x => x > 1).ToList(); list.Add(5); Console.WriteLine(snap.Count); // 3 (snapshot)2 What is the danger of enumerating a query more than once?
mediumEach enumeration re-runs the whole pipeline, so an expensive query or a database call executes again and a side effect in a Select repeats. Results can also change between enumerations. Materialise with ToList when you need the data more than once. Analyser CA1851 warns about this.
csharpint calls = 0; var q = new[] { 1, 2, 3 }.Select(x => { calls++; return x * 2; }); Console.WriteLine(q.Count()); // 3 Console.WriteLine(q.Sum()); // 12 Console.WriteLine(calls); // 6, the pipeline ran twice3 IEnumerable<T> versus IQueryable<T>.
mediumIEnumerable<T> operators take delegates (Func) and run in memory in your process. IQueryable<T> operators take expression trees (Expression<Func>), which a provider such as EF Core translates to SQL and runs at the data source. Calling AsEnumerable or ToList switches to in-memory evaluation, so filtering after that point downloads more rows. A method that accepts IQueryable can compose further filters before the query is executed.
4 Select versus SelectMany.
easySelect maps each element to exactly one result, so a projection to a collection yields a sequence of sequences. SelectMany maps each element to a sequence and flattens them into one, like a nested loop.
csharpvar orders = new[] { new { Id = 1, Items = new[] { "pen", "ink" } }, new { Id = 2, Items = new[] { "pad" } } }; Console.WriteLine(orders.Select(o => o.Items).Count()); // 2 (arrays) Console.WriteLine(string.Join(",", orders.SelectMany(o => o.Items))); // pen,ink,pad5 First, FirstOrDefault, Single and SingleOrDefault: what do they throw?
mediumFirst throws InvalidOperationException on an empty sequence and returns the first element otherwise. FirstOrDefault returns default(T) (null for reference types) when empty. Single throws if there are zero or more than one matches, so it asserts uniqueness. SingleOrDefault throws for more than one match but returns default for none. Use Single for lookups by unique key, and remember default(int) is 0, so a missing int is ambiguous.
6 How do GroupBy and ToLookup differ?
mediumGroupBy is deferred and returns IGrouping<TKey, TElement> items in first-seen key order. ToLookup runs immediately and returns an ILookup you can index by key, returning an empty sequence for missing keys instead of throwing. Both keep elements in source order within each group.
csharpvar words = new[] { "apple", "avocado", "banana", "blueberry", "cherry" }; var g = words.GroupBy(w => w[0]).Select(x => $"{x.Key}:{x.Count()}"); Console.WriteLine(string.Join(" ", g)); // a:2 b:2 c:17 Write an inner join and a left join with LINQ.
mediumJoin matches elements by key and drops those with no match. A left join uses GroupJoin, which produces each outer element with its matching inner group, followed by SelectMany with DefaultIfEmpty to keep outer elements that have no match.
csharpvar emps = new[] { (Id: 1, Name: "Asha", Dept: 10), (Id: 2, Name: "Ravi", Dept: 20), (Id: 3, Name: "Dev", Dept: 99) }; var depts = new[] { (Id: 10, Name: "IT"), (Id: 20, Name: "HR") }; var inner = emps.Join(depts, e => e.Dept, d => d.Id, (e, d) => $"{e.Name}-{d.Name}"); Console.WriteLine(string.Join(",", inner)); // Asha-IT,Ravi-HR var left = from e in emps join d in depts on e.Dept equals d.Id into g from d in g.DefaultIfEmpty() select $"{e.Name}-{(d.Name ?? "none")}"; Console.WriteLine(string.Join(",", left)); // Asha-IT,Ravi-HR,Dev-none8 Any versus Count, and what does All return on an empty sequence?
easyAny() stops at the first element, so it is O(1) for most sources, while Count() may need to enumerate everything (though it is O(1) for collections that expose a count). Prefer Any() for existence. All returns true for an empty sequence (vacuous truth) and Any returns false, a frequent trap.
csharpvar empty = Array.Empty<int>(); Console.WriteLine(empty.All(x => x > 5)); // True Console.WriteLine(empty.Any()); // False9 What does OrderBy guarantee, and how do you sort by multiple keys?
mediumLINQ ordering is stable, so elements with equal keys keep their source order. Use ThenBy and ThenByDescending for secondary keys. Calling OrderBy twice does not combine the keys; the second call re-sorts and only the last key matters (apart from stability).
csharpvar people = new[] { ("Ravi", 30), ("Asha", 25), ("Dev", 30) }; var sorted = people.OrderByDescending(p => p.Item2).ThenBy(p => p.Item1); Console.WriteLine(string.Join(",", sorted.Select(p => p.Item1))); // Dev,Ravi,Asha10 Which set operators and newer helpers should you know?
mediumDistinct removes duplicates, DistinctBy does so by a key, Union is the distinct combination of two sequences, Intersect the common elements and Except the elements of the first that are not in the second. .NET 6 added MaxBy, MinBy, DistinctBy, Chunk, Zip with three sequences and Take with a range; .NET 9 adds CountBy and Index.
csharpvar a = new[] { 1, 2, 2, 3 }; var b = new[] { 2, 3, 4 }; Console.WriteLine(string.Join(",", a.Distinct())); // 1,2,3 Console.WriteLine(string.Join(",", a.Except(b))); // 1 Console.WriteLine(string.Join(",", Enumerable.Range(1, 5).Chunk(2).Select(c => c.Sum()))); // 3,7,511 What does Aggregate do? Write a custom example.
mediumAggregate folds a sequence into one value using an accumulator function and an optional seed. Without a seed the first element is used and the sequence must be non-empty. It is the general form behind Sum and Max.
csharpvar csv = new[] { "a", "b", "c" }.Aggregate((acc, x) => acc + "," + x); Console.WriteLine(csv); // a,b,c Console.WriteLine(Enumerable.Range(1, 5).Aggregate(1, (p, x) => p * x)); // 12012 Predict the output: closures in deferred queries.
hardA lambda captures the variable, not its value at the time the query is written. Since enumeration happens later, it sees the current value, which can produce surprising results when a loop variable or an outer variable changes.
csharpint threshold = 1; var q = new[] { 1, 2, 3 }.Where(x => x > threshold); threshold = 2; Console.WriteLine(string.Join(",", q)); // 3 (uses threshold = 2)13 ToDictionary throws on duplicate keys. How do you handle it?
mediumIt throws ArgumentException when two elements produce the same key. Group first and pick one, use ToLookup, or build the dictionary manually with TryAdd or the indexer to overwrite. Dictionary keys must also be non-null.
csharpvar pairs = new[] { ("a", 1), ("a", 2), ("b", 3) }; var d = pairs.GroupBy(p => p.Item1).ToDictionary(g => g.Key, g => g.Last().Item2); Console.WriteLine(d["a"]); // 214 How would you implement paging with LINQ?
mediumOrder by a stable key, then Skip((page - 1) * size) and Take(size). Always order, otherwise page contents are undefined, and for databases prefer keyset paging (WHERE id > last) on large tables because Skip must still scan the skipped rows.
csharpvar page = items.OrderBy(i => i.Id).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();15 Implement a custom LINQ-style operator with yield return.
hardAn iterator method using yield return is lazy by default, which matches LINQ semantics. Validate arguments in a non-iterator wrapper so exceptions occur at call time, not at first enumeration.
csharpstatic class Ext { public static IEnumerable<T> EveryNth<T>(this IEnumerable<T> src, int n) { ArgumentNullException.ThrowIfNull(src); if (n <= 0) throw new ArgumentOutOfRangeException(nameof(n)); return Iterate(src, n); static IEnumerable<T> Iterate(IEnumerable<T> s, int n) { int i = 0; foreach (var x in s) if (i++ % n == 0) yield return x; } } } Console.WriteLine(string.Join(",", Enumerable.Range(1, 7).EveryNth(3))); // 1,4,716 What is the performance cost of LINQ, and when should you avoid it?
mediumEach operator allocates enumerators and delegate calls, so in hot loops or very small collections a plain for loop can be several times faster and allocation free. Use LINQ for clarity everywhere else. Avoid Count() > 0 (use Any), repeated enumeration, OrderBy to find a minimum (use MinBy) and LINQ-to-Objects over data that should be filtered in the database.
Frequently asked questions
Is LINQ slower than loops?
Usually slightly, because of allocations and delegates. For typical business code the difference is negligible; measure before replacing it.
Query syntax or method syntax?
Both compile to the same calls. Method syntax is more common; query syntax reads better for joins and let clauses.
What is the difference between Count and Count()?
Count is a property on collections (O(1)); Count() is an extension method that uses the property when available and otherwise enumerates.
Where do I practise related C# questions?
See C# collections and C# coding questions.
Related guides
More in Programming Language Interview Questions by Language
- C# OOPs Interview Questions
- C++ Coding Interview Questions
- C++ Interview Questions and Answers
- C++ Memory Management Interview Questions
- C++ OOPS Interview Questions
- C++ Pointers and References Interview Questions
- C++ Smart Pointers Interview Questions
- C++ STL Interview Questions
- C++ Templates Interview Questions
- C++ Virtual Functions Interview Questions
- Core Java Interview Questions for Freshers
- Entity Framework Core Interview Questions