chris.au
chris.au

Reputation: 1108

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)

Upvotes: 14

Views: 2122

Answers (5)

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

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 (e.g. C5 which has a SortedArray and a TreeSet class).

Upvotes: 8

Frank Krueger
Frank Krueger

Reputation: 70993

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.

Upvotes: 1

ram
ram

Reputation: 11626

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

Upvotes: 0

Francisco
Francisco

Reputation: 4101

I think HashSet<int> may suit your needs.

Upvotes: -1

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

You can use a regular List<T> and call Sort on it.

Upvotes: 3

Related Questions