Is there a non-unique-key sorted list generic collection in C#?

kdt picture kdt · Nov 17, 2009 · Viewed 10.7k times · Source

I'm a bit surprised by System.Collections.Generic.SortedList, in that

  1. It requires me to use <key, value> instead of <value>(comparer)
  2. It only allows on entry per value

These seem quirky in the way I want to use it (although I'm sure they're just right for other situations). Is there another collection that doesn't have these two characteristics?

Answer

Marc Gravell picture Marc Gravell · Nov 17, 2009

SortedList<,> is really a map sorted by key, not a list. Bad naming, maybe. But there are ways to emulate what you want, depending on your exact requirements. You could, for example, encapsulate a SortedList<T, int> and have add/remove something like:

// add
int count;
if(list.TryGetValue(value, out count)) list[value] = count+1;
else list[value] = 1;

Ultimately you could use a simple list (List<>) too - it depends what you are doing.

In part, I expect that data-binding etc makes it hard to implement a regular list that sorts immediately - you need to implement a lot of interfaces to get that working, as normally it expects the item you add to stay at the end.