首页 > 解决方案 > How to sort/select top values from Hashtable?

问题描述

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?

标签: c#sortinghashtable

解决方案


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)

推荐阅读