I want to go through a HashSet and make a (complicated) check on each element which results in saving the element, removing the element from the HashSet or doing nothing.
Since a foreach loop does not allow me to change the HashSet and an index is not available, I do not know how to perform the task (without doing slow things like copying the HashSet first or applying several LINQ operations which means enumerating the HashSet more than once).
Any suggestions?
HashSet remove() method is used to remove a particular element from a HashSet.
Set remove() method in Java with Examplesutil. Set. remove(Object O) method is used to remove a particular element from a Set.
To remove a single element from a HashSet, use the remove() method.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
You just need to use RemoveWhere() with an appropriate predicate function.
You can have a side-effect of your predicate which copies the element being checked (assuming that's what you mean by "save the element"), if needed. Perhaps that sounds a little hacky, but it would work fine I think.
This works because your predicate function will be presented with each element of the HashSet in an undefined order, and therefore you can decide what to do with each element, as well as returning true
to delete it and false
to keep it.
[EDIT] Here's a code sample.
using System;
using System.Collections.Generic;
namespace Demo
{
public class Program
{
[STAThread]
private static void Main(string[] args)
{
var hashSet = new HashSet<int> {4, 0, 6, -1, 23, -8, 14, 12, -9, 5, 2};
var itemProcessor = new ItemProcessor();
hashSet.RemoveWhere(itemProcessor.Process);
Console.WriteLine("Max = {0}, Min = {1}", itemProcessor.Max, itemProcessor.Min);
Console.WriteLine("\nHashSet contents:");
foreach (int number in hashSet)
{
Console.WriteLine(number);
}
}
}
public sealed class ItemProcessor
{
private int max = int.MinValue;
private int min = int.MaxValue;
// Removes all negative numbers and calculates max and min values.
public bool Process(int item)
{
max = Math.Max(item, max);
min = Math.Min(item, min);
return (item < 0);
}
public int Max { get { return max; } }
public int Min { get { return min; } }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With