c# - 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)
推荐阅读
- angular - 地理定位插件在Android手机中不起作用
- python - 使用python在pdf文件中写入列表
- c# - 如何通过 UWP 应用正确为灰度图像着色?
- c++ - 为什么我们需要浮点指针或整数指针分别指向浮点变量或整数变量?
- android - 错误:注释类型声明中的元素不能声明形参
- docker - 为什么我们在 Docker Compose 中增加版本?(版本 1、2 和 3)
- c++ - 我修改了 gtest/gmock,所以很容易模拟非虚拟函数
- gcc - STM32:ST-Link 尝试闪存 RAM 区域
- c# - 如何使用设置定义组?
- .net-core - 如何忽略或覆盖 .NET Core Web Api 中的请求标头?