Kolekcje: zbiór HashSet bez powtórzeń
Kolekcje i LINQ - Podstawy C# (csharp)
HashSet<T> to zbiór: każdy element występuje w nim najwyżej raz. Add zwraca false, gdy element już był, co pozwala łatwo wykryć powtórzenia. Zbiory mają operacje matematyczne: IntersectWith (część wspólna), UnionWith (suma) i ExceptWith (różnica). Kolejność elementów zbioru nie jest gwarantowana, dlatego przed wypisaniem sortujemy je metodą LINQ OrderBy.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 4, 7, 4, 1, 9, 7, 4 };
HashSet<int> seen = new HashSet<int>();
foreach (int number in numbers)
{
if (!seen.Add(number))
{
Console.WriteLine($"Powtórzenie: {number}");
}
}
Console.WriteLine($"Różnych liczb: {seen.Count}");
HashSet<string> mathClub = new HashSet<string> { "Ola", "Kuba", "Ewa" };
HashSet<string> itClub = new HashSet<string> { "Kuba", "Adam", "Ewa" };
HashSet<string> both = new HashSet<string>(mathClub);
both.IntersectWith(itClub);
Console.WriteLine($"W obu kółkach: {string.Join(", ", both.OrderBy(n => n))}");
HashSet<string> all = new HashSet<string>(mathClub);
all.UnionWith(itClub);
Console.WriteLine($"Wszyscy: {string.Join(", ", all.OrderBy(n => n))}");
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.