Em1
Em1

Reputation: 1095

Sorting elements in a HashTable, Dictionary or such

I have a set of data consisting of a name and associated content. Thus I'd go with something like HashTable or Dictionary to store those items.

I need to sort these data with two priorities. First they should be in an alphabetical order and then some items should be placed at the beginning in a specific order.

If alphabetical order would be my only requirement I'd use the SortedDictionary. This dictionary sorts the elements automatically based on the key.

What I'm looking for is a class which allows me to do:

  1. Add elements in a random order
  2. Sort all elements in an alphabetical order
  3. Move (or remove and insert) elements to the beginning (or more generic: at any place I want to).

Upvotes: 0

Views: 266

Answers (3)

c0D3l0g1c
c0D3l0g1c

Reputation: 3164

Why not look at SortedList<TKey, TValue>?

That should have appropriate functions to let you do what you want and it's fast for sorting!

Upvotes: 1

Piotr Czarnecki
Piotr Czarnecki

Reputation: 1688

You didn't provide info if names of this data can be duplicated. Generally I think you can use a different ways to hold this data. You should remember that the essence of Dictonaries is hold key/value data where key is unique. The order of elements is not the essence of Dictionaries. This is more List matter in my opinion. So you, can try to mix Dictionary with the Linq to Objects. But maybe try to use Generic

    List< KeyValuePair< TKey, TValue>>.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

There is no built-in collection that does what you need, but you can build your own relatively easily:

  • Write an implementation of IDictionary<TKey,TValue>
  • Put a Dictionary<TKey,TValue> dict and a List<TKey> keys inside
  • When adding an element to dict, also add its key to keys
  • When iteration is requested, iterate keys and then look up entries in the dict

If your collection is organized that way, you'd be able to re-order the keys independently of the dictionary entries. You need to be careful in the implementation because of double "bookkeeping" that should be going on in the operations that change the dictionary. Other than that, the solution should be relatively straightforward.

Upvotes: 1

Related Questions