Skip to content

[API Proposal]: SortedSet<T>.GetAlternateLookup() #108642

Open

Description

@terrajobst

Background and motivation

We added GetAlternateLookup() to many collection types, including Dictionary<TKey, TValue> and HashSet<T>. We should add it to SortedSet<T> as well, for symmetry. In my case, I often use SortedSet<string> over HashSet<T> because I'm persisting data to disk and I'd like to have a stable order to make diffs less jarring.

API Proposal

namespace System.Collections.Generic;

public partial class SortedSet<T>
{
    public readonly struct AlternateLookup<TAlternate>
    {
        public SortedSet<T> Set { get; }
        public bool Add(TAlternate item);
        public bool Contains(TAlternate item);
        public bool Remove(TAlternate item);
        public bool TryGetValue(TAlternate equalValue, [MaybeNullWhen(false)] out T actualValue);
    }

    public AlternateLookup<TAlternate> GetAlternateLookup<TAlternate>();
    public bool TryGetAlternateLookup<TAlternate>(out AlternateLookup<TAlternate> lookup);
}

API Usage

var set = new SortedSet<string>() { "Immo", "Landwerth" };
var lookup = set.GetAlternateLookup<ReadOnlySpan<char>>();

var span = "Immo".AsSpan();
lookup.Contains(span);

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on Oct 8, 2024
  2. added
    untriaged
    on Oct 8, 2024
  3. added
    api-ready-for-review
    and removed
    api-suggestion
    untriaged
    on Oct 8, 2024
  4. added this to the 10.0.0 milestone on Oct 8, 2024
  5. dotnet-policy-service commented on Oct 8, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  6. huoyaoyuan commented on Oct 8, 2024

    @huoyaoyuan
    Member

    A side question: is there any interface support for the alternate lookups? For example, can I use the Dictionary<TKey, TValue>.AlternateLookup<TAlternateKey> as a IDictionary<TAlternateKey, TValue>? The api surface on alternate lookups doesn't naturally provide Keys in alternate key or kvp support, but they can be easily filled. For ISet<T>, the api surface on alternate lookup is significantly smaller.

  7. PaulusParssinen commented on Oct 8, 2024

    @PaulusParssinen
    Contributor

    I attempted API proposal for this at #101694 but I folded pretty quick.

  8. eiriktsarpalis commented on Oct 8, 2024

    @eiriktsarpalis
    Member

    I will repeat the feedback I put in the original issue. Do allocation-heavy tree-based sets with $\mathcal O(\log n)$ lookup warrant the performance improvement of span-based lookups? If we think that it's necessary, don't we also need an IAlternateComparer<T, TAlternate> complement to IComparer<T> that mirrors the IAlternateEqualityComparer<T, TAlternate> interface? Should we extend this to immutable sorted collections?

  9. stephentoub commented on Oct 8, 2024

    @stephentoub
    Member

    If we think that it's necessary, don't we also need an IAlternateComparer<T, TAlternate> complement to IComparer that mirrors the IAlternateEqualityComparer<T, TAlternate> interface?

    For what purpose?

  10. eiriktsarpalis commented on Oct 8, 2024

    @eiriktsarpalis
    Member

    Don't we need a mechanism that determines whether the proposed GetAlternateLookup<TAlternate>(); call succeeds for a particular set?

  11. stephentoub commented on Oct 8, 2024

    @stephentoub
    Member

    Don't we need a mechanism that determines whether the proposed GetAlternateLookup<TAlternate>(); call succeeds for a particular set?

    If we add the Get, we should add the TryGet, too.

  12. eiriktsarpalis commented on Oct 8, 2024

    @eiriktsarpalis
    Member

    I suspect this would be difficult to sign off on without a PoC created ahead of time. @terrajobst should we mark it needs-work or do we want to review the proposal in principle first?

  13. terrajobst commented on Oct 15, 2024

    @terrajobst
    ContributorAuthor

    If we do the work, we probably want to all comparison-based data structures, such as:

    • SortedSet<T>
    • OrderedDictionary<TKey, TValue>
    • SortedDictionary<TKey, TValue>
    • SortedList<TKey, TValue>
    • Immutable?
  14. eiriktsarpalis commented on Oct 15, 2024

    @eiriktsarpalis
    Member

    As well as all binary search methods that accept IComparer<T>.

  15. bartonjs commented on Oct 15, 2024

    @bartonjs
    Member

    Video

    • SortedSet is based on a tree implementation using Compare, not Equals, so the existing IAlternateEqualityComparer is not sufficient.
      • This can realistically only go forward with an IAlternateComparer.
        • It's probably on the order of the same amount of work as when we introduced IAlternateEqualityComparer.
        • And should probably look for other places we could use that.
    namespace System.Collections.Generic;
    
    public partial class SortedSet<T>
    {
        public readonly struct AlternateLookup<TAlternate>
        {
            public SortedSet<T> Set { get; }
            public bool Add(TAlternate item);
            public bool Contains(TAlternate item);
            public bool Remove(TAlternate item);
            public bool TryGetValue(TAlternate equalValue, [MaybeNullWhen(false)] out T actualValue);
        }
    
        public AlternateLookup<TAlternate> GetAlternateLookup<TAlternate>();
        public bool TryGetAlternateLookup<TAlternate>(out AlternateLookup<TAlternate> lookup);
    }
  16. added
    api-needs-work
    and removed
    api-ready-for-review
    on Oct 15, 2024
  17. modified the milestones: 10.0.0, 11.0.0 on Jul 16, 2025
  18. eiriktsarpalis commented on Feb 26, 2026

    @eiriktsarpalis
    Member

    Note

    This proposal was drafted with the help of an AI agent. Please review for accuracy and remove this notice once you're satisfied with the content.

    Background and motivation

    Dictionary<TKey,TValue> and HashSet<T> support allocation-free lookups via AlternateLookup and IAlternateEqualityComparer<TAlternate, T>. However, comparison-based sorted collections (SortedSet<T>, SortedDictionary<TKey,TValue>, SortedList<TKey,TValue>) lack this because they use IComparer<T>, not IEqualityComparer<T>.

    Today, looking up a ReadOnlySpan<char> key in a SortedDictionary<string, TValue> requires allocating a string:

    ReadOnlySpan<char> key = "hello";
    if (dict.TryGetValue(key.ToString(), out var value)) { ... } // allocates

    A new IAlternateComparer<TAlternate, T> interface (analogous to IAlternateEqualityComparer) enables the same allocation-free pattern for sorted collections.

    API Proposal

    namespace System.Collections.Generic;
    
    public interface IAlternateComparer<in TAlternate, T>
        where TAlternate : allows ref struct
        where T : allows ref struct
    {
        int Compare(TAlternate alternate, T other);
        T Create(TAlternate alternate);
    }
    namespace System.Collections.Generic;
    
    public partial class SortedSet<T>
    {
        public SortedSet<T>.AlternateLookup<TAlternate> GetAlternateLookup<TAlternate>() where TAlternate : allows ref struct;
        public bool TryGetAlternateLookup<TAlternate>(out SortedSet<T>.AlternateLookup<TAlternate> lookup) where TAlternate : allows ref struct;
    
        public readonly struct AlternateLookup<TAlternate> where TAlternate : allows ref struct
        {
            public SortedSet<T> Set { get; }
            public bool Add(TAlternate item);
            public bool Contains(TAlternate item);
            public bool Remove(TAlternate item);
            public bool TryGetValue(TAlternate equalValue, out T actualValue);
        }
    }
    
    public partial class SortedDictionary<TKey, TValue>
    {
        public SortedDictionary<TKey, TValue>.AlternateLookup<TAlternateKey> GetAlternateLookup<TAlternateKey>() where TAlternateKey : allows ref struct;
        public bool TryGetAlternateLookup<TAlternateKey>(out SortedDictionary<TKey, TValue>.AlternateLookup<TAlternateKey> lookup) where TAlternateKey : allows ref struct;
    
        public readonly struct AlternateLookup<TAlternateKey> where TAlternateKey : allows ref struct
        {
            public SortedDictionary<TKey, TValue> Dictionary { get; }
            public TValue this[TAlternateKey key] { get; set; }
            public bool ContainsKey(TAlternateKey key);
            public bool Remove(TAlternateKey key);
            public bool Remove(TAlternateKey key, out TValue value);
            public bool TryAdd(TAlternateKey key, TValue value);
            public bool TryGetValue(TAlternateKey key, out TValue value);
        }
    }
    
    public partial class SortedList<TKey, TValue>
    {
        public SortedList<TKey, TValue>.AlternateLookup<TAlternateKey> GetAlternateLookup<TAlternateKey>() where TAlternateKey : allows ref struct;
        public bool TryGetAlternateLookup<TAlternateKey>(out SortedList<TKey, TValue>.AlternateLookup<TAlternateKey> lookup) where TAlternateKey : allows ref struct;
    
        public readonly struct AlternateLookup<TAlternateKey> where TAlternateKey : allows ref struct
        {
            public SortedList<TKey, TValue> List { get; }
            public TValue this[TAlternateKey key] { get; set; }
            public bool ContainsKey(TAlternateKey key);
            public int IndexOfKey(TAlternateKey key);
            public bool Remove(TAlternateKey key);
            public bool Remove(TAlternateKey key, out TValue value);
            public bool TryAdd(TAlternateKey key, TValue value);
            public bool TryGetValue(TAlternateKey key, out TValue value);
        }
    }

    StringComparer subclasses (CultureAwareComparer, OrdinalComparer, OrdinalCaseSensitiveComparer, OrdinalIgnoreCaseComparer) implement IAlternateComparer<ReadOnlySpan<char>, string?>, matching the existing IAlternateEqualityComparer pattern.

    API Usage

    var dict = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
    dict["hello"] = 42;
    
    var lookup = dict.GetAlternateLookup<ReadOnlySpan<char>>();
    
    // Allocation-free lookup
    ReadOnlySpan<char> key = "HELLO";
    if (lookup.TryGetValue(key, out int value))
    {
        Console.WriteLine(value); // 42
    }
    
    // Allocation-free contains
    Console.WriteLine(lookup.ContainsKey(key)); // True
    
    // Insert via span (allocates the key string via Create)
    lookup.TryAdd("world".AsSpan(), 99);
    var set = new SortedSet<string>(StringComparer.Ordinal);
    set.Add("apple");
    
    var lookup = set.GetAlternateLookup<ReadOnlySpan<char>>();
    Console.WriteLine(lookup.Contains("apple".AsSpan())); // True
    lookup.Remove("apple".AsSpan());
    var list = new SortedList<string, int>(StringComparer.Ordinal);
    list["key"] = 1;
    
    var lookup = list.GetAlternateLookup<ReadOnlySpan<char>>();
    int index = lookup.IndexOfKey("key".AsSpan()); // 0

    Design Decisions

    • IAlternateComparer has Compare + Create (no GetHashCode): Comparison-based collections don't need hash codes, unlike IAlternateEqualityComparer which has Equals + GetHashCode + Create.
    • SortedList.AlternateLookup includes IndexOfKey: SortedList uniquely exposes index-based access; the alternate lookup preserves this capability.
    • SortedSet.AlternateLookup.Remove does a double traversal: FindNode with the alternate comparer, then DoRemove with the actual item. This is correct because DoRemove requires the actual T for tree rebalancing. The cost is O(log n) + O(log n) = O(log n).

    Alternative Designs

    • Reuse IAlternateEqualityComparer: Not possible — sorted collections use IComparer<T>, not IEqualityComparer<T>. A comparison requires ordering information (Compare returning int), not just equality (Equals returning bool).
    • Add Compare to IAlternateEqualityComparer: Would pollute the equality-only interface with comparison concerns and break existing implementers.

    Risks

    • No binary breaking changes: Only additive APIs.
    • No source breaking changes: New methods are on new nested types; partial keyword added to existing classes is source-compatible.
    • GenFacades incompatibility: The allows ref struct syntax is not supported by the GenFacades tool used in partial facade assemblies. The new *.AlternateLookup.cs files are excluded from GenFacades processing via <ExcludeFromGenFacades>true</ExcludeFromGenFacades> metadata.

    Open Questions

    • Should immutable sorted collections (ImmutableSortedSet, ImmutableSortedDictionary) also get AlternateLookup? (Suggest as future work.)
    • Should Array.BinarySearch and List<T>.BinarySearch accept IAlternateComparer? (Suggest as future work.)

    Related Issues

    Prototype

    Branch: api-proposal/alternate-comparer
    Commit: 6f0332127b9

  19. modified the milestones: 11.0.0, Future on Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Collections

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions