C# program to remove an item from Set


Firstly, declare a HashSet and add elements −

var names = new HashSet<string>();
names.Add("Tim");
names.Add("John");
names.Add("Tom");
names.Add("Kevin");

To remove an element, use RemoveWhere.

names.RemoveWhere(x => x == "John");

Let us see the complete example −

Example

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      var names = new HashSet < string > ();
      names.Add("Tim");
      names.Add("John");
      names.Add("Tom");
      names.Add("Kevin");
      Console.WriteLine("Initial Set...");
      foreach(var val in names) {
         Console.WriteLine(val);
      }
      names.RemoveWhere(x => x == "John");
      Console.WriteLine("Set after removing an element...");
      foreach(var val in names) {
         Console.WriteLine(val);
      }
   }
}

Updated on: 22-Jun-2020

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements