En C#, HashSet es una colección desordenada de elementos únicos. Esta colección se presenta en NET 3.5 . Admite la implementación de conjuntos y utiliza la tabla hash para el almacenamiento. Esta colección es del tipo genérico colección y está definida en Sistema.Colecciones.Genérico espacio de nombres. Generalmente se usa cuando queremos evitar que se coloquen elementos duplicados en la colección. El rendimiento de HashSet es mucho mejor en comparación con la lista.
Puntos importantes relacionados con HashSet en C#
- La clase HashSet implementa el Colección I , IEnumerable , Colección IReadOnly , septiembre , IEnumerable , IDeserializaciónCallback , y ISerializable interfaces.
- En HashSet, el orden de los elementos no está definido. No puedes ordenar los elementos de HashSet.
- En HashSet, los elementos deben ser únicos.
- En HashSet, no se permiten elementos duplicados.
- Proporciona muchas operaciones matemáticas de conjuntos, como intersección, unión y diferencia.
- La capacidad de un HashSet es la cantidad de elementos que puede contener.
- Un HashSet es una colección dinámica, lo que significa que el tamaño del HashSet aumenta automáticamente cuando se agregan nuevos elementos.
- En HashSet, solo puedes almacenar el mismo tipo de elementos.
¿Cómo crear un HashSet?
La clase HashSet proporciona 7 tipos diferentes de constructores que se utilizan para crear un HashSet, aquí solo usamos HashSet() , constructor. Para leer más sobre los constructores de HashSet, puede consultar C# | Clase HashSet .
HashSet(): Se utiliza para crear una instancia de la clase HashSet que está vacía y utiliza el comparador de igualdad predeterminado para el tipo de conjunto.
Paso 1: Incluir Sistema.Colecciones.Genérico espacio de nombres en su programa con la ayuda de usando palabra clave:
using System.Collections.Generic;>
Paso 2: Cree un HashSet usando la clase HashSet como se muestra a continuación:
HashSet Hashset_name = new HashSet();>
Paso 3: Si desea agregar elementos en su HashSet, utilice Agregar() método para agregar elementos en su HashSet. Y también puedes almacenar elementos en tu HashSet usando el inicializador de colección.
Etapa 4: Se accede a los elementos de HashSet mediante el uso de un para cada bucle. Como se muestra en el siguiente ejemplo.
Ejemplo:
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>>mihash1 =>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>>mihash2 =>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);> >}> >}> }> |
>
>Producción
Elements of myhash1: C C++ C# Java Ruby Elements of myhash2: 10 100 1000 10000 100000>
¿Cómo eliminar elementos del HashSet?
En HashSet, puede eliminar elementos del HashSet. La clase HashSet proporciona tres métodos diferentes para eliminar elementos y los métodos son:
- Quitar(T) : Este método se utiliza para eliminar el elemento especificado de un objeto HashSet.
- Eliminar dónde (predicado) : Este método se utiliza para eliminar todos los elementos que coinciden con las condiciones definidas por el predicado especificado de una colección HashSet.
- Claro : Este método se utiliza para eliminar todos los elementos de un objeto HashSet.
Ejemplo 1:
C#
configuración del navegador web
// 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>>mihash =>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);> >}> }> |
>
>Producción
Total number of elements present in myhash: 5 Total number of elements present in myhash: 4 Total number of elements present in myhash:0>
Establecer operaciones
La clase HashSet también proporciona algunos métodos que se utilizan para realizar diferentes operaciones en conjuntos y los métodos son:
- UniónCon(IEnumerable) : Este método se utiliza para modificar el objeto HashSet actual para que contenga todos los elementos que están presentes en él mismo, en la colección especificada o en ambos.
Ejemplo:
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>>mihash1 =>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>>mihash2 =>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);> >}> >}> }> |
>
>Producción
C C++ C# Java Ruby PHP Perl>
- Intersectarse con (IEnumerable) : Este método se utiliza para modificar el objeto HashSet actual para que contenga solo elementos que están presentes en ese objeto y en la colección especificada.
Ejemplo:
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>>mihash1 =>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>>mihash2 =>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);> >}> >}> }> |
>
>Producción
C++ Java>
- Excepto con (IEnumerable) : Este método se utiliza para eliminar todos los elementos de la colección especificada del objeto HashSet actual.
Ejemplo:
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>>mihash1 =>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>>mihash2 =>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);> >}> >}> }> |
>
>Producción
C C# Ruby>