Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 14

    LINQ Interview Questions: Which Operator to Use and Why

    What this lesson teaches

    These LINQ interview questions explain which operator to use and why: Select or SelectMany, Distinct or DistinctBy, ThenBy or a second OrderBy, First or Single, Any, All, Count or Contains, GroupBy, ToLookup or ToDictionary, the joins (Join, GroupJoin, LeftJoin), Union or Concat, Max or MaxBy, paging with Skip and Take, and when to call ToList.

    Then you solve four classic coding tasks: the second-highest salary per department, duplicate names, word frequency, and the top two orders per customer. The examples use LINQ to Objects: LINQ over .NET collections, not a database.

    Select or SelectMany?

    Use Select when each input item should produce one result. That result can itself be a collection: selecting each order's products gives you one product collection per order. Use SelectMany when you want the products from all those orders in one sequence. See Flattening Nested Data with SelectMany.

    This transformation is called projection: choosing what each input item becomes. Combining the inner sequences is called flattening.

    For example, imagine two orders. One contains Tea and TEA, while the other contains Bread and Tea.

    The mistake to avoid. SelectMany does not remove duplicates. Both occurrences of Tea remain unless you separately ask for distinct results.

    In an interview, say: “Select produces one result per input item. SelectMany produces an inner sequence for each item and flattens those sequences into one. I use Select for one collection per order, and SelectMany for all the products across those orders.”

    Distinct or DistinctBy?

    Distinct removes duplicates by comparing the items themselves. DistinctBy removes duplicates using a selected key, such as a product ID. An equality comparer supplies the rules for deciding whether two items or keys are equal. See Removing Duplicates and Comparing Lists.

    For strings, the choice matters. StringComparer.Ordinal compares exact character values, so Tea and TEA differ. StringComparer.OrdinalIgnoreCase ignores case without using language-specific comparison rules.

    Our example deliberately compares two different jobs:

    • Distinct(StringComparer.Ordinal) keeps distinct product names: Tea, TEA, and Bread.
    • DistinctBy(p => p.Length) keeps one name per length: Tea and Bread.

    DistinctBy requires .NET 6 or later.

    The mistake to avoid. A key must match your definition of a duplicate. Product-name length is useful for this demonstration, but it would merge unrelated products in a real catalogue.

    In an interview, say: “Distinct compares whole items using their equality rules. DistinctBy compares a key I select. I choose the key and comparer to match what the application considers a duplicate.”

    OrderBy or ThenBy?

    Use OrderBy for the primary sorting key, then ThenBy for the next key. A second OrderBy starts a new primary ordering instead of adding a secondary key. The OrderBy remarks explain this ordering rule and the stable sort used below. In this example, priority comes first, and names break priority ties. See Sorting by Several Keys with OrderBy and ThenBy.

    The following is one complete .NET 10 console program. It includes the projection and duplicate examples from above.

    The customer and order entries use tuples, which hold several values together with names such as Id and Name.

    Before running it, predict the two name orders. Will replacing ThenBy with OrderBy make any difference?

    C#Runs
    using System;
    using System.Globalization;
    using System.Linq;
    
    var customers = new[]
    {
        (Id: 1, Name: "Zed", Priority: 2),
        (Id: 2, Name: "Ann", Priority: 2),
        (Id: 3, Name: "Raj", Priority: 1),
        (Id: 4, Name: "Bea", Priority: 1)
    };
    var orders = new[]
    {
        (Id: 101, CustomerId: 4, Total: 900,
            Products: new[] { "Tea", "TEA" }),
        (Id: 102, CustomerId: 2, Total: 700,
            Products: new[] { "Bread", "Tea" })
    };
    
    var nested = orders.Select(o => o.Products).ToArray();
    var products = orders.SelectMany(o => o.Products).ToArray();
    Console.WriteLine("Product collections: " +
        nested.Length.ToString(CultureInfo.InvariantCulture));
    Console.WriteLine("All products: " + string.Join(", ", products));
    
    var byBoth = customers.OrderBy(c => c.Priority)
        .ThenBy(c => c.Name, StringComparer.Ordinal);
    var reordered = customers.OrderBy(c => c.Priority)
        .OrderBy(c => c.Name, StringComparer.Ordinal);
    Console.WriteLine("ThenBy: " + string.Join(", ", byBoth.Select(c => c.Name)));
    Console.WriteLine("OrderBy again: " + string.Join(", ", reordered.Select(c => c.Name)));
    
    var names = products.Distinct(StringComparer.Ordinal);
    var lengths = products.DistinctBy(p => p.Length);
    Console.WriteLine("Distinct names: " + string.Join(", ", names));
    Console.WriteLine("Distinct lengths: " + string.Join(", ", lengths));
    Output
    Product collections: 2
    All products: Tea, TEA, Bread, Tea
    ThenBy: Bea, Raj, Ann, Zed
    OrderBy again: Ann, Bea, Raj, Zed
    Distinct names: Tea, TEA, Bread
    Distinct lengths: Tea, Bread

    First, nested contains two arrays, one per order. products contains four names because SelectMany reads both inner arrays.

    byBoth puts priority 1 first, sorting its names as Bea, Raj. Priority 2 follows as Ann, Zed. Its full output is Bea, Raj, Ann, Zed.

    reordered makes name the main sort key. Its output is Ann, Bea, Raj, Zed.

    The mistake to avoid. Chaining a second OrderBy does not mean “then sort by this.” The second OrderBy sorts the whole list again by the new key. LINQ to Objects sorts stably: items with the same new key keep the order they had before. But the old key is no longer the main order.

    In an interview, say: “I sort by two keys with OrderBy followed by ThenBy. A second OrderBy starts a new primary ordering, so it is not a replacement for ThenBy.”

    First, FirstOrDefault, Single, or SingleOrDefault?

    Choose according to how many results are allowed, not just whether you want to avoid an exception. Default means the value C# supplies when no explicit value is given; for int it is 0.

    First expresses “give me the first available result.” Single expresses “there must be exactly one.” If “first” means newest or highest, establish that ordering before choosing the item. See First, Single, Last and ElementAt.

    An empty integer query followed by FirstOrDefault() returns 0, not null. A nullable value type, written here as int?, can hold an integer or null. Projecting with Select(n => (int?)n) before FirstOrDefault() lets you represent absence separately from zero. See FirstOrDefault for its default-value rules.

    The mistake to avoid. SingleOrDefault does not tolerate duplicates. “OrDefault” changes the no-result case, not the multiple-result case.

    In an interview, say: “First and FirstOrDefault accept multiple matches and return the first. Single and SingleOrDefault reject multiple matches. With no match, First and Single throw; the OrDefault versions return default, which is zero for int unless I use a nullable result.”

    Any, All, Count, or Contains?

    Any() asks whether a sequence contains at least one item. For that question, Any() and Count() > 0 give the same answer on an ordinary collection, but Any states the intent directly and can stop as soon as existence is known. Count asks for the number of items, so it can require reading the whole sequence when a count is not already available. See Any, All and Contains.

    Any(condition) asks whether at least one item passes a condition. All(condition) asks whether every item passes; it returns true for an empty sequence because no item fails. See the return-value rules for All. Contains(item) asks whether a particular item is present, using the applicable equality rules.

    For example, orders.Any(o => o.Total > 800) is true for our orders. products.Contains("tea", StringComparer.Ordinal) is false because neither Tea nor TEA is exactly tea.

    The mistake to avoid. All does not also prove that data exists. If the requirement says “at least one order, and every order qualifies,” check both existence and the condition.

    In an interview, say: “For existence I use Any rather than Count greater than zero. Both answer the same existence question, but Any communicates it and can stop at the first item. All checks that every item passes and stops at the first that fails, while Contains checks membership.”

    Which operator for which job?

    Start with the result you need. The Enumerable documentation lists the operators available for collections.

    JobOperators to consider
    Keep matching itemsWhere; use Any when you only need to know whether a match exists
    SortOrderBy, then ThenBy; descending versions reverse the chosen key's direction
    GroupGroupBy, ToLookup; CountBy and AggregateBy require .NET 9
    JoinJoin, GroupJoin; LeftJoin and RightJoin require .NET 10; FullJoin requires .NET 11
    De-duplicateDistinct, DistinctBy (.NET 6); Union also removes duplicates across inputs
    PageOrderBy with a unique tie-breaker, then Skip and Take; Chunk (.NET 6) makes fixed-size batches
    Look upToDictionary for one item per key; ToLookup for multiple items per key

    GroupBy, ToLookup, or ToDictionary? GroupBy produces groups when you read the query. ToLookup runs now and gives you, for each key, all its items. ToDictionary runs now and gives one item per key; it throws if two items have the same key (ArgumentException). Choose according to whether each key is allowed to have several items. See Converting Results and Building Lookups.

    Join, GroupJoin, or LeftJoin? A join combines items whose selected keys match. Join produces matching pairs; GroupJoin produces one result per outer item with its collection of matches. LeftJoin also keeps outer items with no match, supplying the inner type's default value for the missing side. It was added in .NET 10 (see the LeftJoin reference); the .NET 11 join documentation also describes this behaviour. See Joining In-Memory Data.

    Union or Concat? Concat appends one sequence to another and retains duplicates. Union returns distinct items across both sequences according to the chosen equality comparer. Use Concat when repeated items are meaningful. See Removing Duplicates and Comparing Lists.

    Max or MaxBy? Max finds the greatest value, such as the greatest order total. MaxBy(o => o.Total) returns an order with the greatest total instead. MaxBy and MinBy require .NET 6; if ties matter, specify how your application should resolve them. See Totals and Extremes.

    Skip and Take? Skip discards a specified number of items, and Take keeps up to a specified number. For repeatable pages, sort first and include a unique tie-breaker, such as an order ID. Even a sort that always gives the same order cannot stop a page from changing when the data itself changes. See Paging and Batching.

    When should you call ToList? ToList reads the query now and stores its results in a list. Use it when you need to reuse those results without running the query again, or need list operations. It uses memory for the list. The list holds the same class objects (references), not copies; struct values such as tuples are copied. See Converting Results and Building Lookups.

    The mistake to avoid. ToDictionary is not a substitute for grouping when keys can repeat.

    In an interview, say: “I choose by the required result: one item or many per key, matching pairs or unmatched items too, duplicates retained or removed. I also decide whether the query should run later or its results should be stored now.”

    Four classic coding tasks

    The salary task assumes an employees collection whose entries have Department and integer Salary properties. The other tasks use the program's data or an already-split array named words.

    1. Find the second-highest distinct salary per department.

    Use employees.GroupBy(e => e.Department, StringComparer.Ordinal).Select(g => new { Department = g.Key, Salary = g.Select(e => e.Salary).Distinct().OrderByDescending(s => s).Skip(1).Select(s => (int?)s).FirstOrDefault() }).

    For salaries 900, 900, and 700, Distinct leaves 900 and 700. Descending sorting puts 900 first, and Skip(1) leaves 700. With fewer than two distinct salaries, the nullable projection makes the result null.

    2. Find duplicate product names.

    Use products.GroupBy(p => p, StringComparer.Ordinal).Where(g => g.Count() > 1).Select(g => g.Key).

    Each group contains one exact name's occurrences. Keeping groups with more than one occurrence returns Tea for our example.

    3. Count word frequency.

    Use words.CountBy(w => w, StringComparer.OrdinalIgnoreCase) on .NET 9 or later. It returns each word key with its count, treating case differences as equal here. Splitting punctuation and deciding what counts as a word are separate input-cleaning decisions.

    4. Find the top two orders per customer.

    Use orders.GroupBy(o => o.CustomerId).SelectMany(g => g.OrderByDescending(o => o.Total).ThenBy(o => o.Id).Take(2)).

    Sorting and taking happen inside each customer's group. SelectMany then combines those per-customer results; a customer with only one order contributes one order.

    The mistake to avoid. Skipping one employee is not the same as skipping the highest distinct salary. Without Distinct, the salaries 900, 900, and 700 produce 900 again after Skip(1).

    In an interview, say: “For the second-highest distinct salary, I select salaries, remove duplicates, sort descending, and skip one. Before FirstOrDefault I project to int?, so no second distinct salary returns null rather than zero. For a per-department result, I do that inside each department group.”

    Check yourself

    A query selects each order's product collection. Which change returns one sequence containing all those products, including repeated products?

    A Add ToList after the Select call.
    B Replace Select with SelectMany.
    C Replace Select with GroupBy.
    D Add Distinct after the Select call.
    Show answer

    Correct answer: B

    Option A: ToList stores the separate product collections; it does not combine their contents.

    Option B: SelectMany takes the products from each order and combines them into one sequence, keeping repeated products.

    Option C: GroupBy creates groups rather than combining the products into one sequence.

    Option D: Distinct compares the selected collections; it does not combine their contents.

    An integer salary sequence contains 900, 900, and 700. Which query finds the second-highest distinct salary and returns null when there is no second distinct salary?

    A OrderByDescending, Skip(1), then FirstOrDefault on int.
    B Distinct, OrderByDescending, Take(1), project to int?, then FirstOrDefault.
    C Distinct, OrderByDescending, Skip(1), project to int?, then FirstOrDefault.
    D OrderByDescending, Skip(1), project to int?, then SingleOrDefault.
    Show answer

    Correct answer: C

    Option A: Without Distinct, skipping the first 900 leaves another 900. An empty int result would also return 0, not null.

    Option B: Take(1) keeps the highest distinct salary, 900, instead of moving past it.

    Option C: Distinct removes the repeated 900, and Skip(1) moves past the highest salary. Projecting to int? makes an empty result return null.

    Option D: Sorting and skipping one item leaves 900 and 700. SingleOrDefault throws because two items remain.

    Going deeper

    Deferred execution means a query's work waits until you read its results; Where and Select are deferred, whereas ToList reads immediately.

    IEnumerable<T> queries run in your program; an IQueryable<T> query can be translated by a provider such as EF Core into SQL. See LINQ in C#: What It Is and How a Query Runs.

    A method existing in LINQ does not guarantee that a database provider can translate it into SQL. For broader interview preparation, continue with collections, LINQ, and data structures.

    For version questions, distinguish when an operator appeared from which .NET version your project currently targets:

    • .NET 6: Chunk, MinBy, MaxBy, and DistinctBy.
    • .NET 9: CountBy, AggregateBy, and Index. AggregateBy maintains a calculated result per key; Index pairs items with their positions. See what's new in .NET 9 libraries.
    • .NET 10: LeftJoin, RightJoin, Shuffle, and Sequence. Shuffle produces a random ordering; Sequence generates a numeric sequence. See the API pages for LeftJoin, RightJoin, Shuffle and Sequence.
    • .NET 11: FullJoin keeps unmatched items from both inputs. New overloads without a result function let Join, LeftJoin, RightJoin and FullJoin return named (Outer, Inner) pairs, and let GroupJoin return each outer item as the Key of a group that holds its matches. They need .NET 11. See the .NET 11 join improvements.

    Coding practice

    Apply these choices in Can the parcels be shipped?, then investigate repeated execution in Why does this query run twice?.

    Sources

    Practice

    Practice test: Practice: LINQ Interview Questions: Which Operator to Use and Why10 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·