Codectionary / Developer documentation / C#

Maintain Ordered Unique Values with SortedSet

Combine set uniqueness, sorted traversal and range views with explicit comparison rules.

Read the syntax

Combine set uniqueness, sorted traversal and range views with explicit comparison rules.

Traversal follows ascending integer order.

What it is and why to use it

A set removes duplicates; a sorted set also maintains comparer order. SortedSet is useful for a changing collection that needs ordered traversal and range queries. Its comparer determines both order and equivalence, so it can have a different uniqueness policy from a HashSet using a different equality comparer.

How it works

Add returns false when an equivalent value already exists. GetViewBetween returns a live bounded view backed by the original set, not an independent snapshot. Removing a value through the view changes the original. Adding an out-of-range value through the view is rejected. Mutable elements whose comparison changes can invalidate the intended ordering.

Common mistakes and limitations

Do not mistake a range view for a copy. Do not compare objects by mutable properties while leaving them in the set. For a one-time distinct ordered list, a LINQ pipeline can be simpler than maintaining a specialised collection.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

var set = new SortedSet<int>();
var view = set.GetViewBetween(minimum, maximum);

Examples

Deduplicate and order values

Inspect the sorted result and the return value of a duplicate insertion.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var values = new SortedSet<int> { 3, 1, 3, 2 };
Console.WriteLine(string.Join(", ", values));
Console.WriteLine(values.Add(2));
  1. The repeated 3 is not stored twice.
  2. Traversal follows ascending integer order.
  3. Adding another 2 returns false because an equivalent item already exists.
  4. Expected output: 1, 2, 3 False
  5. Document whether callers receive a live view or a snapshot.

Modify the original through a range view

Keep the live-view relationship visible.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var all = new SortedSet<int> { 1, 2, 3, 4, 5 };
var middle = all.GetViewBetween(2, 4);
Console.WriteLine(string.Join(", ", middle));
middle.Remove(3);
Console.WriteLine(string.Join(", ", all));
  1. The range includes both boundaries under the set’s comparer.
  2. Remove acts through the bounded view.
  3. The final traversal proves the original set also lost 3. Create a separate collection if a detached result is required.
  4. Expected output: 2, 3, 4 1, 2, 4, 5
  5. Document whether callers receive a live view or a snapshot.

Best practices

  • Document whether callers receive a live view or a snapshot.
  • Keep comparison-relevant element data stable.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading