Start learning free

LESSON 233 OF 674 · SETS

Sets in C#

Lesson

TL ; DR:

A HashSet holds values without repeats. Adding a value that is already in it changes nothing.


HashSet<string> pets = new HashSet<string>(new[] {"cat", "dog", "cat"});   // cat goes in once

pets.Add("fish");                            // a new value

pets.Add("dog");                             // already in it, no change

Console.WriteLine(pets.Count);               // 3

Console.WriteLine(pets.Contains("dog"));     // True


Full lesson:

A List keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • new HashSet<string>() makes an empty set of strings.
  • s.Add(x) puts x in the set s. For a repeat, it returns false and changes nothing.
  • s.Contains(x) is true when x is in the set.
  • s.Count gives how many values the set holds.
  • new HashSet<string>(list) builds a set from a list. Its repeats go in once.

Checking s.Contains(x) is fast, even for a big set. A list's Contains looks at the values one by one.

Its size is Count, as for a List. It is not Length.

A set has no order and no indexes. s[0] doesn't compile.


Your task

The camp's sign-up list, names, has some names twice. Build a HashSet named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check