【问题标题】:Getting the max value out of a tuple in a dictionary in C#从 C# 字典中的元组中获取最大值
【发布时间】:2016-02-24 05:26:45
【问题描述】:

我有一个字典声明如下:

Dictionary<Tuple<long, long>, Tuple<double, long>> dict= new Dictionary<Tuple<long, long>, Tuple<double, long>>(); 

如何获取所有字典值中 Item2 的最大值?

【问题讨论】:

  • 字典键是一个元组?
  • 所有字典值中 Item2 的最大值到底是什么意思?
  • Dictionary&lt;Tuple&lt;long, long&gt;, Tuple&lt;double, long&gt;&gt; 听起来像是维护的噩梦,您应该将其更改为更清晰的内容。
  • 为什么你的键是一个元组?一个很好的理由,或者你只是想得到一个项目列表?如果是这样,请改用 List>。您可以在任何 Enumerable 集合的以下答案中使用 Max。如果您愿意,请将您的代码发布在 Code Review 上并在此处链接。可能是一种更好的方式来做你想做的任何事情。

标签: c# dictionary tuples


【解决方案1】:

您可以像这样简单地使用Max LINQ 方法:

long max = dict.Values.Max(x => x.Item2);

【讨论】:

    【解决方案2】:

    您可以使用Max method。不完全清楚您要的是哪一个:

    var maxKey = dict.Max(x => x.Key.Item2);
    var maxValue = dict.Max(x => x.Value.Item2);
    
    var maxEither = Math.Max(dict.Max(x => x.Key.Item2), dict.Max(x => x.Value.Item2));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 2020-07-06
      相关资源
      最近更新 更多