【问题标题】:Better way then sorting dictionary and getting keys only更好的方法,然后对字典进行排序并仅获取键
【发布时间】:2017-11-18 06:16:58
【问题描述】:

我有一个客户字典和相关数据(例如 MoneySpent),并且想只返回排序后的客户列表。 到目前为止,我想出的唯一解决方案是:

CustomerData<Customer, int>  //the value here is the money spent
List<KeyValuePair<Customer, int>> sortedListByValue = CustomerData.OrderByDescending(s => s.Value).ToList();

然后只是遍历列表并获取密钥。不过,我确信有一种更简单的方法,并且很乐意提供建议。

【问题讨论】:

  • 什么是CustomerData?你能在你的代码中显示出来吗?
  • 接受答案的另一种解决方案(嗯,实际上相同,但使用其他语法)是查询语法:var sorted = (from kv in CustomerData orderby kv.Value descending select kv.Value).ToList();

标签: c# sorting dictionary


【解决方案1】:

您可以选择Key,这将为您提供客户。

var sortedListByValue = CustomerData.OrderByDescending(s => s.Value)
    .Select(x => x.Key).ToList();

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多