-2

I have a Hashtable with following content:

jak: 1
dsf: 1
usd: 1
idb: 1
bla: 3
sdd: 1
asd: 2
bsd: 1

I want to select top 10 pairs by value. In this example it would be like that:

bla: 3
asd: 2

etc. How do I do that?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Richard
  • 11
  • 2

1 Answers1

0

If you swap your code to using a dictionary, it'll look like:

var top10 = dict.OrderByDescending(kvp => kvp.Value).Take(10);

You can enumerate top10, which will be a sequence of KeyValuePair, and print their Key and Value properties

You can still do it with a hashtable, by the way (gunr's comment kinda implies that you can't use LINQ) and you can get LINQ to Cast all the entries to make them easier to work with:

hashtable.Cast<DictionaryEntry>().OrderByDescending(de => (int)de.Value).Take(10)
Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • which is faster Hashtable or Dictionary? – Richard Aug 24 '21 at 16:35
  • I would't use Hashtable for new development. In either case this is going to be fairly slow, relatively speaking, because you're sorting potentially a lot of items to discard most. The alternatives are fairly intense though. If you have a specific performance requirement, state it as part of the inquiry. All in i think you'll have to get a very long list before it becomes an issue.. If your question is about raw performance of the dictionary vs hashtable as a data storage device maybe see https://stackoverflow.com/questions/1089132/net-hashtable-vs-dictionary-can-the-dictionary-be-as-fast – Caius Jard Aug 24 '21 at 16:35