.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# SortedSet
C# SortedSet class can be used to store, remove or view elements. It maintains ascending order and does not store duplicate elements. It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order. It is found in System.Collections.Generic namespace.
C# SortedSet example
Let's see an example of generic SortedSet class that stores elements using Add() method and iterates elements using for-each loop.
using System;
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet();
names.Add("Golu");
names.Add("pulkit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Golu");//will not be added
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet();
names.Add("Golu");
names.Add("pulkit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Golu");//will not be added
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output :
Golu
pulkit
Peter
irfan
pulkit
Peter
irfan
C# SortedSet example 2
Let's see another example of generic SortedSet class that stores elements using Collection initializer.
using System;
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet(){ "Anil", "sunil", "Nikhil"};
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
using System.Collections.Generic;
public class SortedSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new SortedSet(){ "Anil", "sunil", "Nikhil"};
// Iterate SortedSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Anil
Sunil
Nikhil
Sunil
Nikhil