如何从字典中获取MAX值? [英] How to get MAX value from Dictionary?

查看:218
本文介绍了如何从字典中获取MAX值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();

我如何获得 Guid MAX 值?

推荐答案

因为这是公认的答案,所以我ll尝试覆盖问题的所有可能含义:

Since this was the accepted answer, I'll try to cover every possible meaning of the question:

var dict = new Dictionary<string, int> { { "b", 3 }, { "a", 4 } };

// greatest key
var maxKey = dict.Keys.Max(); // "b"

// greatest value
var maxValue = dict.Values.Max(); // 4

// key of the greatest value
// 4 is the greatest value, and its key is "a", so "a" is the answer.
var keyOfMaxValue = dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; // "a"

注意:该问题具有 System.Guid 作为键类型。询问什么是最大的GUID可能没有任何意义,因为它们仅是唯一的值,而不是表示任何可排序的概念。尽管如此,以上代码仍可用于支持> 运算符, string int 。

Note: the question has System.Guid as the key type. It might not make sense to ask "what is the greatest GUID", since they are simply intended to be unique values, rather than represent any orderable concept. Nonetheless, the above code will work with any type that supports the > operator, string and int being chosen here for conciseness.

这篇关于如何从字典中获取MAX值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆