🔷 C#

Conjuntos (Set) em C# (.NET 6): guia detalhado

Sets in C#: Unique Collections Without Duplicates

What is a Set and Why Do You Need It?

Imagine you're collecting stickers. You want each sticker to appear only once — no duplicates. That's exactly how a Set works in programming.

A Set is a collection that stores only unique elements. If you try to add an existing element, it simply won't be added. This is very useful when you need to:

  • Remove duplicate words from text
  • Check if an element exists in a collection
  • Merge two lists without duplicates

In C#, the HashSet<T> type is used for working with sets (where T is the element type, e.g., string or int).

Basic Syntax

Create an empty set:

HashSet<string> products = new HashSet<string>();

Create a set with initial elements:

HashSet<string> fruits = new HashSet<string>() { "apple", "banana", "orange" };

Add an element:

products.Add("milk");

Remove an element:

products.Remove("milk");

Check if an element exists:

if (products.Contains("milk"))
{
    Console.WriteLine("Milk is on the list!");
}

Get the number of elements:

int count = products.Count;

Iterate through all elements (each will appear only once):

foreach (string product in products)
{
    Console.WriteLine(product);
}

Main Set Operations

Sets support mathematical operations that are very useful in practice:

Union (UnionWith) — adds all elements from another set or list:

HashSet<string> basic = new HashSet<string>() { "bread", "milk" };
HashSet<string> additional = new HashSet<string>() { "milk", "eggs" };
basic.UnionWith(additional);
// Now basic contains: "bread", "milk", "eggs" (milk was not duplicated!)

Intersection (IntersectWith) — keeps only elements that exist in both sets:

HashSet<string> myIngredients = new HashSet<string>() { "cheese", "tomato", "basil" };
HashSet<string> pizzaRecipe = new HashSet<string>() { "cheese", "sausage", "tomato" };
myIngredients.IntersectWith(pizzaRecipe);
// Now myIngredients contains: "cheese", "tomato"

Difference (ExceptWith) — removes elements that exist in another set:

HashSet<string> shoppingList = new HashSet<string>() { "bread", "milk", "eggs", "butter" };
HashSet<string> alreadyBought = new HashSet<string>() { "milk", "eggs" };
shoppingList.ExceptWith(alreadyBought);
// Now shoppingList contains: "bread", "butter" (what still needs to be bought)

Typical Problem Analysis

Problem: Unique Pizza Ingredients

The user enters ingredients separated by commas. Only unique ones should be displayed.

Console.WriteLine("Enter ingredients separated by commas:");
string input = Console.ReadLine();

// Split the string by commas
string[] ingredients = input.Split(',');

// Create a set — it will automatically remove duplicates
HashSet<string> unique = new HashSet<string>();

foreach (string ingredient in ingredients)
{
    // Remove extra spaces and add
    unique.Add(ingredient.Trim());
}

Console.WriteLine("Unique ingredients:");
foreach (string ingredient in unique)
{
    Console.WriteLine("- " + ingredient);
}

Problem: Merging Party Shopping Lists

Console.WriteLine("Enter your shopping list (separated by commas):");
string yourInput = Console.ReadLine();
string[] yourList = yourInput.Split(',');

Console.WriteLine("Enter the guests' list (separated by commas):");
string guestsInput = Console.ReadLine();
string[] guestsList = guestsInput.Split(',');

// Create a set from the first list
HashSet<string> combinedList = new HashSet<string>();
foreach (string item in yourList)
{
    combinedList.Add(item.Trim());
}

// Add items from guests (duplicates won't be added)
foreach (string item in guestsList)
{
    combinedList.Add(item.Trim());
}

Console.WriteLine("Final shopping list (no duplicates):");
foreach (string item in combinedList)
{
    Console.WriteLine("- " + item);
}

Common Beginner Mistakes

Mistake 1: Trying to access an element by index, like in an array.

// ❌ This won't work
string element = mySet[0]; // Error!

// ✅ Use foreach to iterate or Contains to check

Mistake 2: Forgetting that duplicates aren't added, and assuming Add will return true.

HashSet<string> set = new HashSet<string>();
bool added = set.Add("apple"); // true
bool added2 = set.Add("apple"); // false — apple already exists
// The Add method returns true if the element was actually added

Mistake 3: Not trimming spaces from strings before adding.

// If the user enters: "cheese, tomato, cheese"
// Without Trim() you'll get: " cheese", " tomato", " cheese" — three different elements!
// With Trim(): "cheese", "tomato", "cheese" — duplicates will be removed

Final Example: Contact Notebook

Let's create a program that stores contact names (unique only) and their phone numbers.

// Contact storage: name → set of phone numbers
Dictionary<string, HashSet<string>> contactBook = new Dictionary<string, HashSet<string>>();

while (true)
{
    Console.WriteLine(