C# alternative for the C++ STL set<T>

孤街浪徒 提交于 2019-12-10 21:52:39

问题


I'm looking for a sorted data structure, that will be similar to the STL set(T). I found SortedList, but it requires (key, val), I'm looking for something like List(string) - only sorted.

I found on the web Spring.Collections, but my framework does not recognize it.

Is there a simple SortedSet I could use in the regular basic framework?

Thanks, Gal


回答1:


You can do this with A System.Collections.Generic.Dictionary. Here's a good article: Dictionarys and sorting

Edit: The SortedDictionary seems even better.




回答2:


A SortedSet < T > introduced in .NET 4.0 is what you are looking for, see MSDN here




回答3:


Also List<T> can be sorted. It is not sorted by default, but you can sort it, even with custom sorting algorithms if you so wish.




回答4:


There's nothing built into the framework other than SortedDictionary<K,V> and SortedList<K,V>.

The C5 Collections library has several sorted collections. One of the following should do the trick, depending on your exact requirements: SortedArray<T>, TreeBag<T> or TreeSet<T>.

There's also Power Collections, which provides OrderedBag<T> and OrderedSet<T> collections.




回答5:


There is a System.Collections.SortedList or System.Collections.Generic.SortedList which is always sorted. Or you can use the Array.Sort method to sort ar defined moments in time.




回答6:


How about using a List<> and calling the Sort method?

Not an extension but try this

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();
    }
}

It's only a starting point, but adds a new method AddSort.

An extension method would be used to alter the List<>.Add method and call the sort on the end of it.

Using extension method

Place the following in a namespace accessible by your code:

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

You can the use code such as:

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

And the values will be:

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

You can also just use newList.Add and the list is then sorted when you call newList.AddSort



来源:https://stackoverflow.com/questions/1072786/c-sharp-alternative-for-the-c-stl-sett

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!