typestar

HashSet in C#

A collection that answers one question fast: have I seen this before?

var seen = new HashSet<string> { "read", "eval" };
Console.WriteLine(seen.Add("print"));   // true: it was new
Console.WriteLine(seen.Add("read"));    // false: already there

var other = new HashSet<string> { "eval", "loop" };
seen.IntersectWith(other);
Console.WriteLine(string.Join(",", seen));
Console.WriteLine(seen.Contains("loop"));

How it works

  1. Add returns false instead of storing a duplicate.
  2. IntersectWith mutates the set down to the overlap.
  3. Contains is the constant-time membership test the set exists for.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
339
Tokens
87
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 4 of 4 in Collections, step 14 of 29 in Language basics.

← Previous Next →

HashSet in other languages