CSharp · Console
using System;
using System.Collections.Generic;
namespace HashSetDemo
{
public class Program
{
public static void Main()
{
HashSet<string> names=new HashSet<string>{"Rajeev", "Akash", "Amit"};
foreach(var country in names)
{
Console.WriteLine(country);
}
names.Add("Rajeev");
Console.WriteLine("---------");
//duplicates are not added into collection.
foreach(var name in names)
{
Console.WriteLine(name);
}
//ExceptWith
HashSet<string> names1=new HashSet<string>{"Rajeev", "Akash", "Amit","Deepak","Mohit"};
names1.ExceptWith(names);
Console.WriteLine("-----ExceptWith(elements not present in second(names)----");
foreach(var name in names1)
{
Console.WriteLine(name);
}
//IntersectWith
names.IntersectWith(names1);
Console.WriteLine("-----IntersectWith(elements common----");
foreach(var name in names)
{
Console.WriteLine(name);
}
//UnionWith
names.UnionWith(names1);
Console.WriteLine("-----UnionWith----");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("-----Custom HashSet With Duplicates----");
HashSet<Employee> employees=new HashSet<Employee>
{
{new Employee{Emp_Id=1,Emp_name="Rajeev",Dept_name="IT"}},
{new Employee{Emp_Id=1,Emp_name="Rajeev",Dept_name="IT"}},
{new Employee{Emp_Id=3,Emp_name="Akash",Dept_name="IT"}},
{new Employee{Emp_Id=4,Emp_name="Amit",Dept_name="IT"}}
};
Console.WriteLine("{0,-6}{1,10}{2,-8}","Emp_Id","Emp_name","Dept_name");
Console.WriteLine("==============================");
foreach(var employee in employees)
{
Console.WriteLine("{0,-8}{1,-10}{2,5}",employee.Emp_Id,employee.Emp_name,employee.Dept_name);
}
Console.WriteLine("==============================");
}
}
//Implement IEquatable Interface methods Equals and GetHashCode
public class Employee:IEquatable<Employee>
{
public int Emp_Id{get;set;}
public string Emp_name{get;set;}
public string Dept_name{get;set;}
public bool Equals(Employee other)
{
return this.Emp_Id.Equals(other.Emp_Id);
}
public override int GetHashCode()
{
return this.Emp_Id.GetHashCode();
}
}
}