C# | Eliminar elementos de un HashSet con condiciones definidas por el predicado

Un HashSet es una colección desordenada de elementos únicos. Viene bajo el espacio de nombres System.Collections.Generic . Se utiliza en una situación en la que queremos evitar que se inserten duplicados en la colección. En cuanto al rendimiento, es mejor en comparación con la lista.

El método HashSet<T>.Removewhere(Predicate<T>) se usa para eliminar todos los elementos que coinciden con las condiciones definidas por el predicado especificado de una colección HashSet<T>.

Sintaxis:

public int RemoveWhere (Predicate<T> match);

Valor devuelto: este método devuelve la cantidad de elementos que se eliminaron de la colección HashSet<T>.

Excepción: este método generará ArgumentNullException si la coincidencia es nula.

Nota: Llamar a este método es una operación O(n), donde n es Count, es decir, el número de elementos que están contenidos en el conjunto.

A continuación se muestran los programas para ilustrar el uso del método HashSet<T>.Removewhere(Predicate<T>):

Ejemplo 1:

// C# code to remove elements from a HashSet
// with conditions defined by the predicate
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet = new HashSet<int>();
  
        // Inserting elements into HashSet
        for (int i = 0; i < 10; i++) {
            mySet.Add(i);
        }
  
        Console.WriteLine("The elements in HashSet are : ");
  
        // Displaying the elements in HashSet
        foreach(int i in mySet)
        {
            Console.WriteLine(i);
        }
  
        // Displaying the number of elements in HashSet
        Console.WriteLine("Number of elements are : " + mySet.Count);
  
        // Remove elements from a HashSet
        // with conditions defined by the predicate
        mySet.RemoveWhere(isEven);
  
        Console.WriteLine("The elements in HashSet are : ");
  
        // Displaying the elements in HashSet
        foreach(int i in mySet)
        {
            Console.WriteLine(i);
        }
  
        // Displaying the number of elements in HashSet
        Console.WriteLine("Number of elements are : " + mySet.Count);
    }
  
    // Helper function which tells
    // whether an element is even or not
    private static bool isEven(int i)
    {
        return ((i % 2) == 0);
    }
}
Producción:

The elements in HashSet are : 
0
1
2
3
4
5
6
7
8
9
Number of elements are : 10
The elements in HashSet are : 
1
3
5
7
9
Number of elements are : 5

Ejemplo 2:

// C# code to remove elements from a HashSet
// with conditions defined by the predicate
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet = new HashSet<int>();
  
        // Inserting elements into HashSet
        for (int i = 0; i < 20; i++) {
            mySet.Add(i);
        }
  
        // Displaying the number of elements in HashSet
        Console.WriteLine("Number of elements are : " + mySet.Count);
  
        // Remove elements from a HashSet
        // with conditions defined by the predicate
        mySet.RemoveWhere(myFunc);
  
        // Displaying the number of elements in HashSet
        Console.WriteLine("Number of elements are : " + mySet.Count);
    }
  
    // Helper function which tells
    // whether an element is divisible
    // by both 2 and 3
    private static bool myFunc(int i)
    {
        return ((i % 2) == 0 && (i % 3 == 0));
    }
}
Producción:

Number of elements are : 20
Number of elements are : 16

Referencia:

Publicación traducida automáticamente

Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *