.NET - OOD / OOP - Programming

Custom comparer of a SortedSet

Sorting collections is a common task in programming, and .NET provides a variety of tools to do so efficiently. One such tool is the SortedSet class, which represents a collection of unique elements sorted in ascending or descending order. By default, SortedSet uses the default comparer for its type, but you can also specify a custom comparer to sort the elements based on your own criteria. In this blog post, we’ll explore how to write a custom comparer for a SortedSet in .NET.

The comparer serves two purposes:

  1. define a criterion for ordering items in the set (e.g. the Length property in the sample below), AND
  2. identify duplicate items, so that only one is present in the Set.

Focusing on 1), it is easy to forget about 2), and then have calls to the Add() method of the SortedSet fail with new items that have a sorting property matching that of another item already in the set.

Quick fix: in the comparer, return the relation between the properties used for sorting, and if they match, pick another property of the class that is unique and can differentiate different objects (in the sample below, the Start property cannot be the same for objects with the same Length).

public class ByPatchLength : IComparer<Patch>
    public int Compare(Patch x, Patch y)
        // if lengths are equal, the starting position will differentiate the patches
        if (y.Length == x.Length)
            return y.Start - x.Start;
            return y.Length - x.Length;