dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.17k stars 4.72k forks source link

[API Proposal]: Add TryGetSuccesor() and TryGetPrecessor() for SortedSet. #102253

Open JRichthammer opened 5 months ago

JRichthammer commented 5 months ago

Background and motivation

Because SortedSet is implemented as a binary tree, custom methods to search for a predecessor/successor would be much more performant than searching the whole set until a value greater than the one searched for is found.

TryWeakSuccessor and WeakPredecessor would also be nice.

At the moment I use TreeSet from C5 Library because SortedSet does not offer efficient methods to search for a successor.

API Proposal

namespace System.Collections.Generic;

    public partial class SortedSet<T> : ISet<T>, ICollection<T>, ICollection, IReadOnlyCollection<T>, IReadOnlySet<T>, ISerializable, IDeserializationCallback
    {
            public bool TryGetSuccesor(T equalValue, out T? actualValue);
}
}

API Usage

// Fancy the value
var c = new SortedSet<int>();
c.Add(1);
c.Add(3);

if(c.TryGetSuccesor(2, out int b )){
   System.Console.WriteLine($"Found Successor of 2:{b}"); //Found Successor of 2: 3
}

if(c.TryGetPrecessor(2, out int b )){
   System.Console.WriteLine($"Found Precessor of 2:{b}"); //Found Precessor of 2: 1
}

Alternative Designs

No response

Risks

No response

bill-poole commented 5 months ago

I also use TreeSet<T> (and TreeDictionary<K, V>) from the C5 library for this purpose. It would be very nice if this were supported by the runtime SortedSet<T> (and SortedDictionary<K, V>) classes.