Skip to content

[API Proposal]: Sort() on OrderedDictionary #115127

Open
@jhudsoncedaron

Description

@jhudsoncedaron

Background and motivation

We've had an OrderedDictionary<TK, TV> for a long time; and up comes a stock OrderedDictionary in .NET 9. Kind of an ugly breaking change but there's things I can do about that.

I'd like to replace my junky implementation with the stock implementation; however in order to do that I would need a method added to the stock OrderedDictionary: Sort()

API Proposal

namespace System.Collections.Generic;

public class OrderedDictionary<TK, TV> : /* unchanged */
{
    /* Actual method needed */
    public void Sort(int index, int count, IComparer<KeyValuePair<TK, TV>> comparer);

    /* Standard expected helper method */
    public void Sort(IComparer<KeyValuePair<TK, TV>> comparer) => Sort(0, Count, comparer);
}

API Usage

OrderedDictionary<long, ListItem<long, string>> GetList()
{
    var dict = new OrderedDictionary<long, ListItem<long, string>>();
    /* Populate the dictionary; say from an SQL Query */
    
    dict.Sort(0, dict.Length, new IndirectComparer());
    return dict;
}

private class IndirectComparer: IComparer<KeyValuePair<long, ListItem<long, string>> {
    int Compare(KeyValuePair<long, ListItem<long, string> x, KeyValuePair<long, ListItem<long, string> y)
    {
        if (x.Value is null) return y.Value is null ? 0 : -1;
        if (y.Value is null) return 1;
        return x.Value.CompareTo(y.Value); /* Assume this handles localized sort */
    }
}

Alternative Designs

Add the Swap(int, int) method and I can provide the sort. Without the Swap method an external sort will perform horribly and I must keep using my own junky implementation.

Risks

Potential source breaking change if somebody added a Sort() method into a derived class.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.CollectionsuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions