Remove elements from a HashSet with conditions defined by the predicate in C#

CsharpServer Side ProgrammingProgramming

To remove elements from a HashSet with conditions defined by the predicate, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return (i == 100);
   }
   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(300);
      list.Add(400);
      list.Add(500);
      list.Add(600);
      Console.WriteLine("HashSet elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveWhere(demo);
      Console.WriteLine("HashSet after removing element 100...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

HashSet elements...
100
300
400
500
600
HashSet after removing element 100...
300
400
500
600

Example

Let us see another example −

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 10) == 0);
   }
   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(355);
      list.Add(400);
      list.Add(555);
      list.Add(600);
      Console.WriteLine("HashSet elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveWhere(demo);
      Console.WriteLine("HashSet after removing some elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

HashSet elements...
100
355
400
555
600
HashSet after removing some elements...
355
555
raja
Published on 05-Dec-2019 10:30:06
Advertisements