C# program to remove an item from Set

CsharpProgrammingServer Side Programming

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);
      }
   }
}
raja
Published on 21-Aug-2018 08:36:45
Advertisements