Search Engine Implementation in C#
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
Search Engine in C#: what you actually reach for
C# implementation
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 FreeThe C#-specific trap
Performance in C#, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
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).
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 trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.