Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Search Engine Implementation in C#

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Search Engine runs in O(n log n) time and O(n) space, in C# as in every other language.
  • ✓Dictionary<string, List<Posting>> built with StringComparer.Ordinal, PriorityQueue<TElement, TPriority> from System.Collections.Generic for a bounded top-k, and CollectionsMarshal.GetValueRefOrAddDefault (System.Runtime.InteropServices) to bump a counter with one hash lookup instead of TryGetValue plus an indexer store.
  • ✓Reviewers insist the term dictionary is constructed with StringComparer.Ordinal -- the default for string keys already is ordinal, but writing it makes the intent reviewable and blocks a later culture-sensitive swap.
  • ✓The C# trap: ref var slot = ref CollectionsMarshal.GetValueRefOrAddDefault(map, term, out _) hands you an interior pointer into the Dictionary's private entries array.
  • ✓Generics are reified, so List<Posting> over a readonly record struct is a flat Posting[] with no boxing and no per-element header -- the same index that costs a JVM hundreds of megabytes of Integer objects stays a contiguous array here.

What Search Engine actually is

A search engine is an inverted index plus a ranker. Indexing tokenizes each document, normalizes the tokens, and appends (docId, termFrequency) to a postings list per term; building or merging those sorted runs is the O(n log n). Querying pulls one postings list per query term, intersects or unions them, scores each candidate with something like BM25, and keeps the top k in a bounded heap. You reach for it the moment LIKE '%x%' stops finishing and users start expecting relevance, not just matches.

Search Engine in C#: what you actually reach for

Dictionary<string, List<Posting>> built with StringComparer.Ordinal, PriorityQueue<TElement, TPriority> from System.Collections.Generic for a bounded top-k, and CollectionsMarshal.GetValueRefOrAddDefault (System.Runtime.InteropServices) to bump a counter with one hash lookup instead of TryGetValue plus an indexer store. ReadOnlySpan<char> with string.AsSpan() tokenizes with zero substring allocations until a term is actually interned into the dictionary. System.Globalization.CompareInfo covers locale rules. Lucene.NET is the port of the Java engine; Microsoft.Data.Sqlite reaches FTS5 for the embedded case.

C# implementation

Reviewers insist the term dictionary is constructed with StringComparer.Ordinal -- the default for string keys already is ordinal, but writing it makes the intent reviewable and blocks a later culture-sensitive swap. ToLowerInvariant, never ToLower. Posting is a `readonly record struct`, not a class. LINQ is fine in the query builder and rejected in the scoring loop, and OrderByDescending().Take(k) is flagged specifically because it sorts the entire candidate set where a k-sized PriorityQueue would not.
csharp
using System.Runtime.InteropServices;

public readonly record struct Posting(int Doc, int Tf);

public sealed class InvertedIndex
{
    private readonly Dictionary<string, List<Posting>> _postings = new(StringComparer.Ordinal);
    private readonly Dictionary<int, int> _lengths = new();

    // one analyzer, shared by the index path and the query path
    private static bool NextToken(ReadOnlySpan<char> span, ref int i, out Range token)
    {
        while (i < span.Length && !char.IsLetterOrDigit(span[i])) i++;
        int start = i;
        while (i < span.Length && char.IsLetterOrDigit(span[i])) i++;
        token = start..i;
        return i > start;
    }

    public void Add(int doc, string text)
    {
        ReadOnlySpan<char> span = text.AsSpan();
        var tf = new Dictionary<string, int>(StringComparer.Ordinal);
        var bySpan = tf.GetAlternateLookup<ReadOnlySpan<char>>();   // .NET 9
        Span<char> buf = stackalloc char[64];
        int i = 0, len = 0;
        while (NextToken(span, ref i, out Range r))
        {
            ReadOnlySpan<char> raw = span[r];
            if (raw.Length > buf.Length) raw = raw[..buf.Length];
            ReadOnlySpan<char> tok = buf[..raw.ToLowerInvariant(buf)];
            if (bySpan.TryGetValue(tok, out int c)) bySpan[tok] = c + 1;
            else
            {
                // one string per distinct term, never one per occurrence
                ref int slot = ref CollectionsMarshal.GetValueRefOrAddDefault(tf, new string(tok), out _);
                slot = 1;              // use immediately: the next add invalidates this ref
            }
            len++;
        }
        _lengths[doc] = len;
        foreach (var (term, n) in tf)
        {
            if (!_postings.TryGetValue(term, out var list))
                _postings[term] = list = new List<Posting>();
            list.Add(new Posting(doc, n));
        }
    }

    public List<(int Doc, double Score)> Search(string query, int k = 10)
    {
        int n = _lengths.Count;
        var scores = new Dictionary<int, double>();
        var bySpan = _postings.GetAlternateLookup<ReadOnlySpan<char>>();
        ReadOnlySpan<char> span = query.AsSpan();
        Span<char> buf = stackalloc char[64];
        int i = 0;
        // same analyzer as Add: query.Split(' ') would never match a punctuated term
        while (NextToken(span, ref i, out Range r))
        {
            ReadOnlySpan<char> raw = span[r];
            if (raw.Length > buf.Length) raw = raw[..buf.Length];
            ReadOnlySpan<char> tok = buf[..raw.ToLowerInvariant(buf)];
            if (!bySpan.TryGetValue(tok, out var list)) continue;
            double idf = Math.Log(1 + (n - list.Count + 0.5) / (list.Count + 0.5));
            foreach (var p in list)
                scores[p.Doc] = scores.GetValueOrDefault(p.Doc) + idf * p.Tf / (p.Tf + 1.2);
        }
        var top = new PriorityQueue<int, double>();
        foreach (var (doc, s) in scores)
        {
            top.Enqueue(doc, s);
            if (top.Count > k) top.Dequeue();
        }
        var results = new List<(int, double)>(top.Count);
        while (top.TryDequeue(out int d, out double s)) results.Add((d, s));
        results.Reverse();
        return results;
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The C#-specific trap

ref var slot = ref CollectionsMarshal.GetValueRefOrAddDefault(map, term, out _) hands you an interior pointer into the Dictionary's private entries array. The next insert that triggers a resize allocates a brand-new array, and your ref still points at the abandoned one: every later write through it lands in a buffer nobody reads, with no exception, no compiler complaint and no GC crash because the old array is still reachable from your ref. Term frequencies simply come out short. Consume the ref before touching the dictionary again; never cache one across the token loop or pass it to a helper.

Performance in C#, beyond the O(n log n)

Generics are reified, so List<Posting> over a readonly record struct is a flat Posting[] with no boxing and no per-element header -- the same index that costs a JVM hundreds of megabytes of Integer objects stays a contiguous array here. Dictionary stores each entry's hash code next to the key, so a resize rehashes nothing and a lookup compares ints before it ever compares strings. Tiered compilation runs the scoring loop at tier-0 for its first calls, so measure after warmup. foreach over List<T> uses a struct enumerator and allocates nothing -- assigning it to IEnumerable<T> boxes it once per query. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Search Engine between languages.

Real-World Applications

Search Engine applies wherever its problem shape appears in your own code. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Search Engine helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Search Engine appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Search Engine over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Search Engine to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

Frequently Asked Questions

Which C# type or library should I use for Search Engine?

Dictionary<string, List<Posting>> built with StringComparer.Ordinal, PriorityQueue<TElement, TPriority> from System.Collections.Generic for a bounded top-k, and CollectionsMarshal.GetValueRefOrAddDefault (System.Runtime.InteropServices) to bump a counter with one hash lookup instead of TryGetValue plus an indexer store. ReadOnlySpan<char> with string.AsSpan() tokenizes with zero substring allocations until a term is actually interned into the dictionary. System.Globalization.CompareInfo covers locale rules. Lucene.NET is the port of the Java engine; Microsoft.Data.Sqlite reaches FTS5 for the embedded case.

What is the most common C# mistake when implementing Search Engine?

ref var slot = ref CollectionsMarshal.GetValueRefOrAddDefault(map, term, out _) hands you an interior pointer into the Dictionary's private entries array. The next insert that triggers a resize allocates a brand-new array, and your ref still points at the abandoned one: every later write through it lands in a buffer nobody reads, with no exception, no compiler complaint and no GC crash because the old array is still reachable from your ref. Term frequencies simply come out short. Consume the ref before touching the dictionary again; never cache one across the token loop or pass it to a helper.

How does Search Engine actually perform in C#?

Generics are reified, so List<Posting> over a readonly record struct is a flat Posting[] with no boxing and no per-element header -- the same index that costs a JVM hundreds of megabytes of Integer objects stays a contiguous array here. Dictionary stores each entry's hash code next to the key, so a resize rehashes nothing and a lookup compares ints before it ever compares strings. Tiered compilation runs the scoring loop at tier-0 for its first calls, so measure after warmup. foreach over List<T> uses a struct enumerator and allocates nothing -- assigning it to IEnumerable<T> boxes it once per query. Time complexity is O(n log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Devin free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.