HashSet у C# з прикладами
У C# HashSet — це невпорядкована колекція унікальних елементів. Ця колекція представлена в .NET 3.5 . Він підтримує реалізацію наборів і використовує хеш-таблицю для зберігання. Ця колекція є колекцією загального типу, і вона визначена в System.Collections.Generic простір імен. Зазвичай він використовується, коли ми хочемо запобігти розміщенню повторюваних елементів у колекції. Продуктивність HashSet набагато краща порівняно зі списком.
Важливі моменти, пов’язані з HashSet у C#
- Клас HashSet реалізує ICollection , IEnumerable , IReadOnlyCollection , вересень , IEnumerable , IDeserializationCallback , і ISerializable інтерфейси.
- У HashSet порядок елементів не визначено. Ви не можете сортувати елементи HashSet.
- У HashSet елементи мають бути унікальними.
- У HashSet не допускаються повторювані елементи.
- Він забезпечує багато математичних операцій із наборами, таких як перетин, об’єднання та різниця.
- Ємність HashSet - це кількість елементів, які він може містити.
- HashSet — це динамічна колекція, тобто розмір HashSet автоматично збільшується, коли додаються нові елементи.
- У HashSet можна зберігати лише елементи одного типу.
Як створити хеш-набір?
Клас HashSet забезпечує 7 різних типів конструкторів які використовуються для створення HashSet, тут ми використовуємо лише HashSet() , конструктор. Щоб дізнатися більше про конструктори HashSet, ви можете звернутися до C# | Клас HashSet .
HashSet(): Він використовується для створення екземпляра класу HashSet, який є порожнім і використовує компаратор рівності за замовчуванням для типу набору.
Крок 1: Включати System.Collections.Generic простір імен у вашій програмі за допомогою використовуючи ключове слово:
using System.Collections.Generic;
крок 2: Створіть HashSet за допомогою класу HashSet, як показано нижче:
HashSet Hashset_name = new HashSet();
крок 3: Якщо ви хочете додати елементи у свій HashSet, використовуйте Додати() для додавання елементів у ваш HashSet. Ви також можете зберігати елементи у своєму HashSet за допомогою ініціалізатора колекції.
крок 4: Доступ до елементів HashSet здійснюється за допомогою a для кожного петля. Як показано в прикладі нижче.
приклад:
C#
// C# program to illustrate how to> // create hashset> using> System;> using> System.Collections.Generic;> class> GFG {> > // Main Method> > static> public> void> Main()> > {> > // Creating HashSet> > // Using HashSet class> > HashSet <> string> >myhash1 => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash1.Add(> 'C'> );> > myhash1.Add(> 'C++'> );> > myhash1.Add(> 'C#'> );> > myhash1.Add(> 'Java'> );> > myhash1.Add(> 'Ruby'> );> > Console.WriteLine(> 'Elements of myhash1:'> );> > // Accessing elements of HashSet> > // Using foreach loop> > foreach> (> var> val> in> myhash1)> > {> > Console.WriteLine(val);> > }> > // Creating another HashSet> > // using collection initializer> > // to initialize HashSet> > HashSet <> int> >myhash2 => new> HashSet <> int> >() {10,>> > 100,1000,10000,100000};> > > // Display elements of myhash2> > Console.WriteLine(> 'Elements of myhash2:'> );> > foreach> (> var> value> in> myhash2)> > {> > Console.WriteLine(value);> > }> > }> }> |
Вихід
Elements of myhash1: C C++ C# Java Ruby Elements of myhash2: 10 100 1000 10000 100000
Як видалити елементи з HashSet?
У HashSet ви можете видаляти елементи з HashSet. Клас HashSet надає три різні методи для видалення елементів, і ці методи:
- Видалити (T) : Цей метод використовується для видалення зазначеного елемента з об’єкта HashSet.
- RemoveWhere(предикат) : Цей метод використовується для видалення всіх елементів, які відповідають умовам, визначеним вказаним предикатом, із колекції HashSet.
- ясно : Цей метод використовується для видалення всіх елементів з об’єкта HashSet.
приклад 1:
C#
// C# program to illustrate how to> // remove elements of HashSet> using> System;> using> System.Collections.Generic;> class> GFG {> > // Main Method> > static> public> void> Main()> > {> > // Creating HashSet> > // Using HashSet class> > HashSet <> string> >myhash => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash.Add(> 'C'> );> > myhash.Add(> 'C++'> );> > myhash.Add(> 'C#'> );> > myhash.Add(> 'Java'> );> > myhash.Add(> 'Ruby'> );> > // Before using Remove method> > Console.WriteLine(> 'Total number of elements present (Before Removal)'> +> > ' in myhash: {0}'> , myhash.Count);> > // Remove element from HashSet> > // Using Remove method> > myhash.Remove(> 'Ruby'> );> > // After using Remove method> > Console.WriteLine(> 'Total number of elements present (After Removal)'> +> > ' in myhash: {0}'> , myhash.Count);> > // Remove all elements from HashSet> > // Using Clear method> > myhash.Clear();> > Console.WriteLine(> 'Total number of elements present'> +> > ' in myhash:{0}'> , myhash.Count);> > }> }> |
Вихід
Total number of elements present in myhash: 5 Total number of elements present in myhash: 4 Total number of elements present in myhash:0
Набір операцій
Клас HashSet також надає деякі методи, які використовуються для виконання різних операцій над наборами, а це:
- UnionWith(IEnumerable) : Цей метод використовується для зміни поточного об’єкта HashSet, щоб він містив усі елементи, які присутні в ньому самому, у вказаній колекції або в обох.
приклад:
C#
// C# program to illustrate set operations> using> System;> using> System.Collections.Generic;> class> GFG {> > static> public> void> Main()> > {> > // Creating HashSet> > // Using HashSet class> > HashSet <> string> >myhash1 => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash1.Add(> 'C'> );> > myhash1.Add(> 'C++'> );> > myhash1.Add(> 'C#'> );> > myhash1.Add(> 'Java'> );> > myhash1.Add(> 'Ruby'> );> > // Creating another HashSet> > // Using HashSet class> > HashSet <> string> >myhash2 => new> HashSet <> string> >();>> > // Add the elements in HashSet> > // Using Add method> > myhash2.Add(> 'PHP'> );> > myhash2.Add(> 'C++'> );> > myhash2.Add(> 'Perl'> );> > myhash2.Add(> 'Java'> );> > // Using UnionWith method> > myhash1.UnionWith(myhash2);> > foreach> (> var> ele> in> myhash1)> > {> > Console.WriteLine(ele);> > }> > }> }> |
Вихід
C C++ C# Java Ruby PHP Perl
- IntersectWith(IEnumerable) : Цей метод використовується для зміни поточного об’єкта HashSet, щоб він містив лише елементи, які присутні в цьому об’єкті та у вказаній колекції.
приклад:
C#
// C# program to illustrate set operations> using> System;> using> System.Collections.Generic;> class> GFG {> > // Main Method> > static> public> void> Main()> > {> > // Creating HashSet> > // Using HashSet class> > HashSet <> string> >myhash1 => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash1.Add(> 'C'> );> > myhash1.Add(> 'C++'> );> > myhash1.Add(> 'C#'> );> > myhash1.Add(> 'Java'> );> > myhash1.Add(> 'Ruby'> );> > // Creating another HashSet> > // Using HashSet class> > HashSet <> string> >myhash2 => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash2.Add(> 'PHP'> );> > myhash2.Add(> 'C++'> );> > myhash2.Add(> 'Perl'> );> > myhash2.Add(> 'Java'> );> > // Using IntersectWith method> > myhash1.IntersectWith(myhash2);> > foreach> (> var> ele> in> myhash1)> > {> > Console.WriteLine(ele);> > }> > }> }> |
Вихід
C++ Java
- ExceptWith(IEnumerable) : Цей метод використовується для видалення всіх елементів у вказаній колекції з поточного об’єкта HashSet.
приклад:
C#
// C# program to illustrate set operations> using> System;> using> System.Collections.Generic;> class> GFG {> > // Main Method> > static> public> void> Main()> > {> > // Creating HashSet> > // Using HashSet class> > HashSet <> string> >myhash1 => new> HashSet <> string> >();> > // Add the elements in HashSet> > // Using Add method> > myhash1.Add(> 'C'> );> > myhash1.Add(> 'C++'> );> > myhash1.Add(> 'C#'> );> > myhash1.Add(> 'Java'> );> > myhash1.Add(> 'Ruby'> );> > // Creating another HashSet> > // Using HashSet class> > HashSet <> string> >myhash2 => new> HashSet <> string> >();>> > // Add the elements in HashSet> > // Using Add method> > myhash2.Add(> 'PHP'> );> > myhash2.Add(> 'C++'> );> > myhash2.Add(> 'Perl'> );> > myhash2.Add(> 'Java'> );> > // Using ExceptWith method> > myhash1.ExceptWith(myhash2);> > foreach> (> var> ele> in> myhash1)> > {> > Console.WriteLine(ele);> > }> > }> }> |
Вихід
C C# Ruby