Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 227
kdt Avatar asked Nov 17 '09 09:11

kdt


People also ask

Can sorted list have duplicate keys?

A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.

Can sorted list have duplicates C#?

As you probably know, you can create collections of items without duplicates by using a HashSet<T> object. It is quite useful to remove duplicates from a list of items of the same type.

Which collection type represents a collection of key and value pairs that are sorted by keys and are accessible by keys and values?

C# - SortedList<TKey, TValue> The SortedList<TKey, TValue> , and SortedList are collection classes that can store key-value pairs that are sorted by the keys based on the associated IComparer implementation.

What is a SortedList in C#?

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.


1 Answers

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.

like image 56
Marc Gravell Avatar answered Sep 19 '22 15:09

Marc Gravell