我有一个 List<KeyValuePair<int, string>>
。
我想知道哪个 KeyValuePair<int, string>
具有最大的 Key
。
但是,我想获取键的值,而不仅仅是键本身。
我能做到这一点:
int myValue = myListe.Max(t => t.Key);
但它返回的是键名...而不是键值 :(
我该怎么做?
OrderBy[Descending]
最终是一个排序操作,相对而言比较昂贵 - 例如 O(n log(n)) - 而单次“maxby”只需要 O(n)。 - Marc GravellFirstOrDefault
或 First
来选择所需的 KeyValuePair
,并配合使用 Max
。var list = new List<KeyValuePair<int, string>>();
list.Add(new KeyValuePair<int, string>(1, "a"));
list.Add(new KeyValuePair<int, string>(5, "b"));
list.Add(new KeyValuePair<int, string>(3, "c"));
var value = list.FirstOrDefault(x => x.Key == list.Max(y => y.Key));
var maxVal = list.Max(x => x.Key); var res = list.Single(p => p.Key == maxVal);
- 应该会好得多!另外:如果有重复项怎么办 - 可能需要用 First
而不是 Single
- 基本上就是这样:https://dotnetfiddle.net/uv8icw - Marc Gravell
MaxBy
函数。 - Yacoub MassadSortedDictionary<int, string>
可能会有所帮助。 - Thorsten Dittmar