HashSet en C# amb exemples

En C#, HashSet és una col·lecció no ordenada d'elements únics. Aquesta col·lecció s'introdueix a .NET 3.5 . Admet la implementació de conjunts i utilitza la taula hash per a l'emmagatzematge. Aquesta col·lecció és de tipus genèric i es defineix a System.Collections.Generic espai de noms. S'utilitza generalment quan volem evitar que es col·loquin elements duplicats a la col·lecció. El rendiment del HashSet és molt millor en comparació amb la llista.

Punts importants relacionats amb HashSet en C#

  • La classe HashSet implementa el Icol·lecció , IEnumerable , IReadOnlyCollection , setembre , IEnumerable , IDserializationCallback , i SErialitzable interfícies.
  • A HashSet, l'ordre de l'element no està definit. No podeu ordenar els elements de HashSet.
  • A HashSet, els elements han de ser únics.
  • A HashSet, no es permeten elements duplicats.
  • Proporciona moltes operacions matemàtiques de conjunts, com ara intersecció, unió i diferència.
  • La capacitat d'un HashSet és el nombre d'elements que pot contenir.
  • Un HashSet és una col·lecció dinàmica que significa que la mida del HashSet augmenta automàticament quan s'afegeixen els nous elements.
  • A HashSet, només podeu emmagatzemar el mateix tipus d'elements.

Com crear un HashSet?

La classe HashSet proporciona 7 tipus diferents de constructors que s'utilitzen per crear un HashSet, aquí només fem servir HashSet() , constructor. Per obtenir més informació sobre els constructors de HashSet, podeu consultar C# | Classe HashSet .

HashSet(): S'utilitza per crear una instància de la classe HashSet que està buida i utilitza el comparador d'igualtat predeterminat per al tipus de conjunt.

Pas 1: Incloure System.Collections.Generic espai de noms al vostre programa amb l'ajuda de utilitzant paraula clau:

using System.Collections.Generic; 

Pas 2: Creeu un HashSet utilitzant la classe HashSet tal com es mostra a continuació:

HashSet Hashset_name = new HashSet(); 

Pas 3: Si voleu afegir elements al vostre HashSet, feu servir Afegeix () mètode per afegir elements al vostre HashSet. I també podeu emmagatzemar elements al vostre HashSet mitjançant l'inicialitzador de col·leccions.

Pas 4: S'accedeix als elements de HashSet mitjançant a per cadascú bucle. Com es mostra a l'exemple següent.

Exemple:

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);> > }> > }> }>

Sortida

Elements of myhash1: C C++ C# Java Ruby Elements of myhash2: 10 100 1000 10000 100000 

Com eliminar elements del HashSet?

A HashSet, podeu eliminar elements del HashSet. La classe HashSet proporciona tres mètodes diferents per eliminar elements i els mètodes són:

  • Elimina (T) : Aquest mètode s'utilitza per eliminar l'element especificat d'un objecte HashSet.
  • RemoveWhere (predicat) : Aquest mètode s'utilitza per eliminar tots els elements que compleixen les condicions definides pel predicat especificat d'una col·lecció HashSet.
  • Clar : Aquest mètode s'utilitza per eliminar tots els elements d'un objecte HashSet.

Exemple 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);> > }> }>

Sortida

Total number of elements present in myhash: 5 Total number of elements present in myhash: 4 Total number of elements present in myhash:0 

Establir operacions

La classe HashSet també proporciona alguns mètodes que s'utilitzen per realitzar diferents operacions en conjunts i els mètodes són:

  • UnionWith(IEnumerable) : Aquest mètode s'utilitza per modificar l'objecte HashSet actual perquè contingui tots els elements que estan presents en si mateix, la col·lecció especificada o tots dos.

Exemple:

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);> > }> > }> }>

Sortida

C C++ C# Java Ruby PHP Perl 
  • IntersectWith(IEnumerable) : Aquest mètode s'utilitza per modificar l'objecte HashSet actual perquè contingui només elements presents en aquest objecte i a la col·lecció especificada.
    Exemple:

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);> > }> > }> }>

Sortida

C++ Java 
  • ExceptWith(IEnumerable) : Aquest mètode s'utilitza per eliminar tots els elements de la col·lecció especificada de l'objecte HashSet actual.

Exemple:

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);> > }> > }> }>

Sortida

C C# Ruby