简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM