Is it possible to sort a HashTable?

前端 未结 11 720
不知归路
不知归路 2021-01-17 10:13

I have a property that returns a HashTable. I would like to sort it without refactoring my property. Please note: I do not want to return another type.

相关标签:
11条回答
  • 2021-01-17 10:46

    Another option is to construct the hash table as you're already doing, and then simply construct a sorted set from the keys. You can iterate through that sorted key set, fetching the corresponding value from the hash table as needed.

    0 讨论(0)
  • 2021-01-17 10:47

    You can also use DataView to sort the Hashtable. Here is an article that I wrote 5 years ago: http://www.codeproject.com/Articles/37039/Sorting-Hashtable

    0 讨论(0)
  • 2021-01-17 10:52

    Not exactly a C# answer but I am sure you can make something of it.

    In Perl it is common to "sort" a hash table for use in output to the display.

    For example:

    print "Items: ";
    foreach (sort keys %items) {
        print $_, '=', $items{$_}, ' ';
    }
    

    The trick here is that Perl doesn't sort the hash, it is sorting a copied list of hash keys. It should be easy enough in C# to extract the hash keys into a list and then sort that list.

    0 讨论(0)
  • 2021-01-17 10:52

    Of course hash tables can be sorted, but you need to first define what it means to sort a hash table. (Therein lies the issue)

    Once you have done that, however, you've invariably removed all the advantages that a hashtable can give you, and you might as well use a sorted array (with binary searching), or use a red-black tree instead.

    0 讨论(0)
  • 2021-01-17 10:56

    Hashtables work by mapping keys to values. Implicit in this mapping is the concept that the keys aren't sorted or stored in any particular order.

    However, you could take a look at SortedDictionary<K,V>.

    0 讨论(0)
  • 2021-01-17 10:57

    There is no point in sorting a hash table because you already have almost constant lookup time. Or at worst O(B) where B is the bucket size.

    0 讨论(0)
提交回复
热议问题