简体   繁体   中英

Why does sorted list have to have a key value pair?

If I just want a sorted list of just dates, integers, or doubles is it really necessary to have to define a SortedList(of Integer, Integer)?

Seems intriguing to me, but may just be trival. I'd prefer just to use a SortedList(of Integer).

(This question is in relation to the .Net generic collections)

The next version of .NET (4.0) will have the SortedSet class that exactly does what you want. Until then, encapsulating SortedList gets closest – unless you want to implement an own class to do this, or use external collection libraries (eg C5 which has a SortedArray and a TreeSet class).

您可以使用常规List<T>并在其上调用Sort

Yes it's necessary, because that's how the API was designed. :-)

But it's not hard to just make your own SortedList<T> that uses SortedList<K,V> . 5 lines of code?

class SortedList<T> : IEnumerable<T> {
    SortedList<T,int> _list = new SortedList<T,int>();
    public IEnumerator<T> GetEnumerator() { return _list.Keys.GetEnumerator(); }
    IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator();  }
    public void Add(T v) { _list.Add(v, 1); }
    public int Count { get { return _list.Count; } }
}

Only problem is, SortedList can't handle dups.

Sorted list sorts on the key and not on the values. From MSDN

The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.

So its basically a dictionary class that supports sorting. List on the other hand sorts on values

我认为HashSet<int>可能适合您的需求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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