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
Addreturns false instead of storing a duplicate.IntersectWithmutates the set down to the overlap.Containsis the constant-time membership test the set exists for.
Keywords and builtins used here
newstringvar
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.
Step 4 of 4 in Collections, step 14 of 29 in Language basics.