LinqScenarioQuestions

C# Question Bank

LINQ | 10 Scenario Questions (5 Moderate + 5 Complex) — Questions Only

Instruction: Students should implement ONLY the methods marked with // ✅ TODO.
Each question includes complex sample input (spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹). Replace it with your own as required.
Do not add answers in this page.
Moderate: 5 Complex: 5 Coverage: Where/Select/Distinct, Sorting, GroupBy, Join, Any/All, Left Join, Top-N per group, Set Ops + Comparer, SelectMany + Sum, Pivot Summary
1

Clean Product Names — Where + Select + Distinct

LINQWhereSelectDistinctModerate

Scenario: An admin exports product names. Names may contain extra spaces, mixed casing and symbols. Goal: produce a clean unique list. What to implement: - ProductCleaner.GetUniqueNames(List<string> rawNames) Rules: - Trim, remove empty - Convert to Title Case style (first letter uppercase, rest lowercase) for each word - Remove duplicate names (case-insensitive) - Preserve unicode/emoji ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q1
{
    public static class ProductCleaner
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> GetUniqueNames(List<string> rawNames)
        {
            // TODO:
            // - validate list
            // - trim and remove empty
            // - normalize casing per word (Title Case)
            // - distinct case-insensitive
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var raw = new List<string> { "  laptop stand  ", " LAPTOP   STAND ", "  headphones; noise-cancel  ", "  ", "  cable-α12 ✅  " };
            var names = ProductCleaner.GetUniqueNames(raw);

            Console.WriteLine("Clean Names:");
            names.ForEach(Console.WriteLine);
        }
    }
}
2

Sort Tickets — OrderBy + ThenBy

LINQOrderByThenByModerate

Scenario: Support tickets are collected as strings. Format: "PRIORITY|CreatedAt|TicketId|User" Priority can be P0, P1, P2. Goal: sort by Priority (P0 highest), then by CreatedAt ascending. What to implement: - TicketSorter.Sort(List<string> lines) Rules: - Ignore invalid lines - Treat extra spaces as noise - Output original normalized line format without changing TicketId characters ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q2
{
    public static class TicketSorter
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> Sort(List<string> lines)
        {
            // TODO:
            // - parse valid lines into (priorityRank, createdAt, originalNormalized)
            // - order by priorityRank then createdAt
            // - return sorted normalized lines
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var lines = new List<string>
            {
                " P1 | 2026-02-18 10:05 | TKT-α12 | Sana @ Chennai ✅ ",
                " P0 | 2026-02-18 09:59 | TKT-!@# | Ravi ",
                " P2 | 2026-02-18 09:58 | TKT-β77 | Arjun | extra ",
                " bad-line "
            };

            var sorted = TicketSorter.Sort(lines);

            Console.WriteLine("Sorted:");
            sorted.ForEach(Console.WriteLine);
        }
    }
}
3

Group Logins By City — GroupBy

LINQGroupByCountModerate

Scenario: Login logs are strings: "USER=<name>|CITY=<city>|IP=<ip>" Goal: group by CITY (case-insensitive, trimmed) and count logins. What to implement: - LoginAnalytics.CountByCity(List<string> logs) Rules: - Ignore logs missing CITY - City may contain spaces and special chars ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // Dictionary
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q3
{
    public static class LoginAnalytics
    {
        // ✅ TODO: Student must implement only this method
        public static Dictionary<string, int> CountByCity(List<string> logs)
        {
            // TODO:
            // - parse CITY from each line
            // - normalize city (trim + case-insensitive grouping)
            // - group and count
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var logs = new List<string>
            {
                "USER=Sana|CITY=Chennai|IP=10.0.0.5",
                "USER=Ravi|CITY=  chennai  |IP=10.0.0.8",
                "USER=Arjun|CITY=Bengaluru #02|IP=10.0.0.9",
                "USER=Priya✅|IP=10.0.0.1"
            };

            var map = LoginAnalytics.CountByCity(logs);

            foreach (var kv in map)
                Console.WriteLine($"{kv.Key} => {kv.Value}");
        }
    }
}
4

Join Orders and Customers — Join

LINQJoinProjectionModerate

Scenario: You have Customers and Orders. Join them to produce a report: OrderId, CustomerName, Amount. Rules: - CustomerName may contain spaces, unicode, emoji - Orders may contain unknown CustomerId -> skip those What to implement: - Reports.BuildOrderReport(List<Customer> customers, List<Order> orders) ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q4
{
    public record Customer(int Id, string Name);           // customer entity
    public record Order(string OrderId, int CustomerId, decimal Amount);

    public static class Reports
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> BuildOrderReport(List<Customer> customers, List<Order> orders)
        {
            // TODO:
            // - join orders with customers on CustomerId
            // - project string: "<OrderId> | <CustomerName> | ₹ <Amount>"
            // - order by amount desc
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var customers = new List<Customer>
            {
                new Customer(1, "Sana @ Chennai ✅"),
                new Customer(2, "Ravi")
            };

            var orders = new List<Order>
            {
                new Order("O-90 01", 1, 1999.25m),
                new Order("O-β77", 99, 10.00m)
            };

            var report = Reports.BuildOrderReport(customers, orders);
            report.ForEach(Console.WriteLine);
        }
    }
}
5

Validate Basket — Any/All Rules

LINQAnyAllValidationModerate

Scenario: A shopping basket contains items with Quantity and Name. Rules: - Basket is valid if all quantities > 0 AND at least one item name contains "₹" or "offer" (case-insensitive). What to implement: - BasketValidator.IsValid(List<Item> items) ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q5
{
    public record Item(string Name, int Qty);

    public static class BasketValidator
    {
        // ✅ TODO: Student must implement only this method
        public static bool IsValid(List<Item> items)
        {
            // TODO:
            // - all qty > 0
            // - any name contains "₹" OR "offer" (case-insensitive)
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var items = new List<Item>
            {
                new Item("Offer Pack ₹199", 1),
                new Item("  cable-α12  ", 2),
                new Item("freebie", 0)
            };

            Console.WriteLine("Valid? " + BasketValidator.IsValid(items));
        }
    }
}
6

Left Join: Products With Optional Discounts — GroupJoin

LINQGroupJoinDefaultIfEmptyLeft JoinComplex

Scenario: Not every product has a discount. You must produce a final price list for ALL products. If discount missing, discount% = 0. What to implement: - Pricing.BuildFinalPrices(List<Product> products, List<Discount> discounts) Rules: - Left join on SKU (case-insensitive, trimmed) - FinalPrice = Price * (1 - DiscountPercent/100) - Round 2 decimals ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q6
{
    public record Product(string Sku, string Name, decimal Price);
    public record Discount(string Sku, decimal Percent);

    public static class Pricing
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> BuildFinalPrices(List<Product> products, List<Discount> discounts)
        {
            // TODO:
            // - perform left join using GroupJoin
            // - match sku case-insensitive + trimmed
            // - compute final price and round to 2 decimals
            // - format: "<Sku> | <Name> | ₹ <FinalPrice>"
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var products = new List<Product>
            {
                new Product("SKU-α12", "Laptop Stand", 1299.50m),
                new Product("SKU-β77", "Headphones;NC", 7999m)
            };

            var discounts = new List<Discount>
            {
                new Discount(" sku-β77 ", 10m),
                new Discount(" SKU-!@# ", 5m)
            };

            var list = Pricing.BuildFinalPrices(products, discounts);
            list.ForEach(Console.WriteLine);
        }
    }
}
7

Top 2 Orders Per Customer — GroupBy + OrderBy + Take

LINQGroupByTakeRankingComplex

Scenario: You need the top 2 highest orders per customer for a dashboard. What to implement: - OrderInsights.TopNPerCustomer(List<Order> orders, int n) Rules: - CustomerName may contain spaces/unicode - For each customer, order by Amount desc and take N - Output a flattened list of strings for display ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q7
{
    public record Order(string CustomerName, string OrderId, decimal Amount);

    public static class OrderInsights
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> TopNPerCustomer(List<Order> orders, int n)
        {
            // TODO:
            // - validate inputs
            // - GroupBy customer (case-sensitive ok)
            // - within each group sort desc and Take(n)
            // - flatten to list
            // - format: "<Customer> | <OrderId> | ₹ <Amount>"
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var orders = new List<Order>
            {
                new Order("Sana @ Chennai ✅", "O-1", 1999.25m),
                new Order("Sana @ Chennai ✅", "O-2", 499.00m),
                new Order("Sana @ Chennai ✅", "O-3", 2999.99m),
                new Order("Ravi", "O-4", 150.00m)
            };

            var top2 = OrderInsights.TopNPerCustomer(orders, 2);
            top2.ForEach(Console.WriteLine);
        }
    }
}
8

Detect Policy Violations — Except + Custom Comparer

LINQExceptIEqualityComparerSet OpsComplex

Scenario: Security team has two lists: - AllowedUsers (from HR) - LoginUsers (from audit logs) Goal: 1) Find logins done by users not in AllowedUsers (case-insensitive, trimmed) 2) Find allowed users who never logged in (missing) What to implement: - SecurityOps.FindUnexpectedLogins(...) - SecurityOps.FindNeverLoggedIn(...) ✅ Implement ONLY the TODO methods.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q8
{
    public class UserComparer : IEqualityComparer<string>
    {
        // ✅ TODO: Student must implement only this method
        public bool Equals(string? x, string? y)
        {
            // TODO: compare case-insensitive after trim; handle nulls
            throw new NotImplementedException();
        }

        // ✅ TODO: Student must implement only this method
        public int GetHashCode(string obj)
        {
            // TODO: hash normalized string (trim + lower)
            throw new NotImplementedException();
        }
    }

    public static class SecurityOps
    {
        // ✅ TODO: Student must implement only this method
        public static List<string> FindUnexpectedLogins(List<string> allowed, List<string> loggedIn)
        {
            // TODO: return loggedIn EXCEPT allowed using UserComparer
            throw new NotImplementedException();
        }

        // ✅ TODO: Student must implement only this method
        public static List<string> FindNeverLoggedIn(List<string> allowed, List<string> loggedIn)
        {
            // TODO: return allowed EXCEPT loggedIn using UserComparer
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var allowed = new List<string> { " Sana @ Chennai ✅ ", " Ravi ", " Priya-β " };
            var logged  = new List<string> { "ravi", "  unknown_user#1  ", " Sana @ Chennai ✅ ", " INTRUDER!! " };

            var unexpected = SecurityOps.FindUnexpectedLogins(allowed, logged);
            var missing = SecurityOps.FindNeverLoggedIn(allowed, logged);

            Console.WriteLine("Unexpected:");
            unexpected.ForEach(Console.WriteLine);

            Console.WriteLine("Never Logged In:");
            missing.ForEach(Console.WriteLine);
        }
    }
}
9

Revenue Aggregation From Mixed Text — SelectMany + Sum

LINQSelectManySumParsingComplex

Scenario: You receive daily sales text blocks. Each block contains multiple lines: "SKU=<sku>|QTY=<qty>|PRICE=<money>" Goal: calculate total revenue across all blocks. What to implement: - RevenueCalc.TotalRevenue(List<string> dailyBlocks) Rules: - Money may be "₹ 1,999.25" or "1999.25" (remove commas/currency) - Ignore invalid lines but count valid ones - Return total revenue rounded to 2 decimals ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // List
using System.Globalization;                               // CultureInfo
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q9
{
    public static class RevenueCalc
    {
        // ✅ TODO: Student must implement only this method
        public static decimal TotalRevenue(List<string> dailyBlocks)
        {
            // TODO:
            // - split blocks into lines (SelectMany)
            // - parse qty and price from each valid line
            // - sum qty*price
            // - round 2 decimals
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var blocks = new List<string>
            {
                "SKU=SKU-α12|QTY=2|PRICE=₹ 1,999.25\nSKU=SKU-β77|QTY=1|PRICE=₹ 7,999\nbad|line",
                "SKU=SKU-!@#|QTY=3|PRICE= 499.00 "
            };

            var total = RevenueCalc.TotalRevenue(blocks);
            Console.WriteLine($"Total Revenue: ₹ {total}");
        }
    }
}
10

Pivot Summary — GroupBy + Dictionary (City -> (Dept -> Count))

LINQGroupByNested GroupDictionaryComplex

Scenario: Employee records come as text: "EMP=<name>|CITY=<city>|DEPT=<dept>" Goal: Build a nested summary: City -> Department -> EmployeeCount Rules: - Normalize city and dept: trim + case-insensitive keys - Ignore invalid lines - Keep original city display as Title Case in output keys What to implement: - EmployeePivot.Build(List<string> lines) ✅ Implement ONLY the TODO method.

✅ Sample input intentionally contains spaces, quotes, unicode α/β, emoji ✅, special chars, currency ₹.
LINQ scenario (students implement ONLY TODO methods) Ctrl+C
using System;                                           // Console
using System.Collections.Generic;                          // Dictionary
using System.Linq;                                        // LINQ

namespace ItTechGenie.M1.Linq.Q10
{
    public static class EmployeePivot
    {
        // ✅ TODO: Student must implement only this method
        public static Dictionary<string, Dictionary<string, int>> Build(List<string> lines)
        {
            // TODO:
            // - parse CITY and DEPT
            // - normalize keys (trim + lower for grouping)
            // - produce nested Dictionary with Title Case display keys
            throw new NotImplementedException();
        }
    }

    internal class Program
    {
        static void Main()
        {
            var lines = new List<string>
            {
                "EMP=Sana @ Chennai ✅|CITY= chennai |DEPT=  IT ",
                "EMP=Ravi|CITY=Chennai|DEPT=it",
                "EMP=Arjun|CITY= Bengaluru #02 |DEPT= QA#1 ",
                "EMP=Priya-β|CITY=bengaluru #02|DEPT=qa#1",
                "broken-line"
            };

            var pivot = EmployeePivot.Build(lines);

            foreach (var city in pivot.Keys)
            {
                Console.WriteLine("CITY: " + city);
                foreach (var dept in pivot[city])
                    Console.WriteLine($"  {dept.Key} => {dept.Value}");
            }
        }
    }
}