Skip to main content

Practice · 4 of 4

Debug: The Query in the Loop

CHALLENGE
Difficulty: intermediate+25 XP

A price checker "works" but re-runs a whole LINQ query *inside* the per-item loop, and its cache check uses List.Contains on top. For 1 item it is invisible; for a catalog it is quadratic. The broken shape: ``csharp public static string Check(List<string> catalog, string sku) // BROKEN { if (catalog.Contains(sku)) return "known"; var cheap = catalog.Where(s => s.Length < 4).Count(); // query per call! return cheap > 0 ? "cheap-others" : "unknown"; } ` Write Solution.BuildChecker(IEnumerable<string> catalog) returning a delegate Func<string, string> with the same contract ("known" / "cheap-others" / "unknown") but with ALL expensive work done once at build time: - membership via a prebuilt HashSet, - the cheap-count computed once at build, - the returned delegate does no LINQ and no list scans. `csharp public static class Solution { public static System.Func<string, string> BuildChecker(System.Collections.Generic.IEnumerable<string> catalog); } // provided: public static class ScanProbe { public static int Scans; public static IEnumerable<string> Src(params string[] xs); } ``

Back to lesson: Practice: Performance Practice: Build, Pick, Materialize