2009-07-02 60 views
3

我正在寻找一个有序的数据结构,它与STL集(T)类似。 我发现SortedList,但它需要(键,val),我正在寻找类似List(字符串)的东西 - 只有排序。用于C++ STL集的C#替代方案<T>

我在网上找到Spring.Collections,但我的框架无法识别它。

是否有一个简单的SortedSet我可以在常规的基本框架中使用?

感谢, 加

+1

列表不是一套。你想允许重复吗? – tobsen 2010-12-13 20:49:09

+0

[在.NET中是否有排序的集合类型?](http://stackoverflow.com/questions/196512/is-there-a-sorted-collection-type-in​​-net) – nawfal 2014-06-02 18:28:30

回答

7

你可以用System.Collections.Generic.Dictionary做到这一点。这里有一篇好文章:Dictionarys and sorting

编辑: SortedDictionary似乎甚至better

+0

谢谢。但这正是我想要避免的:有。我正在寻找一个只有值的排序数据结构,如列表,但我想没有,所以我会用你的解决方案。 :-) – 2009-07-02 06:52:28

1

另外List<T>可以排序。它不是默认排序的,但是如果您愿意的话,您可以对它进行排序,即使使用自定义排序算法。

-1

如何使用列表<>并调用Sort方法?

不是一个扩展,但尝试这个

public class SortedList<T>: List<T> 
{ 
    public SortedList(): base() 
    { 
    } 
    public SortedList(IEnumerable<T> collection): base(collection) 
    { 
    } 
    public SortedList(int capacity) 
     : base(capacity) 
    { 
    } 

    public void AddSort(T item) 
    { 
     base.Add(item); 
     this.Sort(); 
    } 
} 

这只是一个起点,但增加了一个新的方法AddSort。

将使用扩展方法来更改列表<> .Add方法并在其末尾调用排序。

使用扩展方法

将在您的代码访问的命名空间中的以下内容:

public static class ListExtension 
{ 
    public static void AddSort<T>(this List<T> list, T item) 
    { 
     list.Add(item); 
     list.Sort(); 
    } 
} 

您可以使用代码,如:

List<int> newList = List<int>(); 
newList.AddSort(6); 
newList.AddSort(4); 
newList.AddSort(3); 

,并将值成为:

newList [ 0] == 3 newList [1] == 4 newList [3] == 6

您也可以只使用则newList.Add和列表进行排序,当你调用newList.AddSort

0

有是一个System.Collections.SortedList或System.Collections.Generic.SortedList它总是排序。 或者你可以使用Array.Sort方法来按时间排序定义的时刻。

5

的SortedSet,< T>介绍在.NET 4.0中是你在找什么,请参阅MSDN here