简体   繁体   English

C#没有SortedList <T> ?

[英]C# has no SortedList<T>?

I'm trying to solve a problem in which it would be useful to have a data structure like 我正在尝试解决一个像数据结构一样有用的问题

var list = new SortedList<int>(); 
list.Add(3); // list = { 3 } 
list.Add(1); // list = { 1, 3 }
list.Add(2); // list = { 1, 2, 3 }
int median = list[list.Length / 2];

ie

  • O(n) insertion O(n)插入
  • O(1) lookup by index O(1)按索引查找

but I can't see that such a thing exists? 但我看不出这样的事情存在? I see that there's some confusing SortedList<T,U> and then an interface SortedList , but neither of those are what I'm looking for. 我看到有一些令人困惑的SortedList<T,U>然后是一个接口SortedList ,但这些都不是我正在寻找的。

The sorted list in the .NET framework is an associative list (that is it is for key/value pairs). .NET框架中的排序列表是一个关联列表(即用于键/值对)。 You can use a regular List<T> if you use its binary search functionality, which works if you keep the list sorted at all times. 如果使用其二进制搜索功能,则可以使用常规List<T>如果始终对列表进行排序,则可以使用该功能。 You can encapsulate it in an extension method: 您可以将其封装在扩展方法中:

static class SortedListExtensions {
    public static void SortedAdd<T>(this List<T> list, T value) {
        int insertIndex = list.BinarySearch(value);
        if (value < 0) {
            value = ~value;
        }
        list.Insert(insertIndex, value);
    }

    //Added bonus: a faster Contains method
    public static bool SortedContains<T>(this List<T> list, T value) {
        return list.BinarySearch(value) >= 0;
    }
}


List<int> values = new List<int>();
values.SortedAdd(3);
values.SortedAdd(1);
values.SortedAdd(2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM