Home

Tuesday, 12 July 2016

HashSet and its method with Example Using C#

HashSet is collection which stored unique element in unordered manner.In HashSet perform below operation like-
1) Add
2) Remove
3) Contains
4) Clear 
5) CopyTo etc.

Syntax-
HashSet<int> hashset=new HashSet<int>();

1) Add Element in Hashset-
hashset.Add(1);
hashset.Add(2);
hashset.Add(3);
hashset.Add(4);

2) Remove Element from HashSet-
hashset.remove("Element name");
hashset.RemoveWhere(s=>s=="Elementname");

3)Clear  HashSet
hashset.clear();

Example-

using System;
using System.Collections;
namespace TestApp
{  
  class Program
    {
        static void Main(string[] args)
        {
           HashSet<string> name = new HashSet<string> ();
  //Adding Element
  name.Add("Pankaj");
  name.Add("Ravi");
  name.Add("Kushal");
  name.Add("Amar");
          //Remove Element
            name.RemoveWhere(s=>s.Contains("Ravi"));
foreach (string npa in name)
{
Console.WriteLine(npa);
}
        }
    }
}

3 comments:

  1. Please provide a complete example of contains and copyTo in hashset

    ReplyDelete
    Replies
    1. hashset1.CopyTo(collectionanme);

      Delete
    2. hashset1.contains("test1"); its return boolean value if test1 avaailable in hashset1 then its return true.

      Delete