14

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)

EyeDub
  • 38
  • 5
chris.au
  • 1,088
  • 2
  • 15
  • 41
  • possible duplicate of [Is there a SortedList class in .net ? (not SortedList which is actually a kind of SortedDictionnary)](http://stackoverflow.com/questions/389813/is-there-a-sortedlistt-class-in-net-not-sortedlistkey-value-which-is-act) – nawfal Jul 08 '14 at 16:38

5 Answers5

8

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).

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 6
    SortedSet will not add an element that is equal to the one already in the set, as the set theory requires. A SortedList should be able to handle multiple instances of the same value and sort them correctly. – gligoran Aug 12 '11 at 00:52
3

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

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
1

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.

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
  • Just need to also implement non-generic ienumerable. See http://stackoverflow.com/questions/8760322/troubles-implementing-ienumerablet . I've edited it for you. – Patrick Szalapski Apr 22 '14 at 03:36
0

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

ram
  • 11,468
  • 16
  • 63
  • 89
-1

I think HashSet<int> may suit your needs.

Francisco
  • 4,104
  • 3
  • 24
  • 27