.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# HashSet
C# HashSet class can be used to store, remove or view elements. It does not store duplicate elements. It is suggested to use HashSet class if you have to store only unique elements. It is found in System.Collections.Generic namespace.
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet();
names.Add("Anil");
names.Add("Sunil");
names.Add("mohan");
names.Add("deelip");
names.Add("Anil");//will not be added
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet();
names.Add("Anil");
names.Add("Sunil");
names.Add("mohan");
names.Add("deelip");
names.Add("Anil");//will not be added
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Anil
Sunil
mohan
deelip
Sunil
mohan
deelip