【问题标题】:List.IndexOf() - return index of final occurrence rather than the first?List.IndexOf() - 返回最终出现的索引而不是第一个?
【发布时间】:2014-10-10 09:39:46
【问题描述】:
int highestValue = someList.IndexOf(someList.Max())

someList 包含很多重复项, someList.Max() 返回最大值的第一个实例的索引。

我可以使用一些技巧(反转列表的顺序吗?)来获取列表中最高值的最终出现的索引,而不是求助于编写手动方法?

【问题讨论】:

  • 仅供参考,变量highestValue 的名称有误。
  • 有更好的implementation。您当前的一个不是最优的,需要 2 次通过:1)找到最大值 2)找到等于最大值的索引值。

标签: c# list ienumerable


【解决方案1】:

试试这个:

int highestValue = someList.LastIndexOf(someList.Max()) ;

【讨论】:

    【解决方案2】:

    所有其他答案都完全正确,必须注意这需要对列表进行 2 次迭代(一次找到最大元素,第二次找到最后一个索引)。对于一个非问题的整数列表,但如果迭代更复杂,这里有一个替代方案:

    var highestValue = someList.Select((val, ind) => new { Value = val, Index = ind })
                               .Aggregate((x, y) => (x.Value > y.Value) ? x : y)
                               .Index;
    

    【讨论】:

      【解决方案3】:

      你的意思是想得到index of the last occurrence?那将是:

      int highestValueIndex = someList.LastIndexOf(someList.Max())
      

      但是,您应该意识到您正在使 two 传递原始代码和上面代码中的数据。如果您想一次性完成(并且只有在您的数据集很大时才应该担心这一点),您可以通过以下方式执行此操作:

      static int LastIndexOfMax(List<int> list)
      {
          // Empty list, no index.
      
          if (list.Count == 0) return -1;
      
          // Default to first element then check all others.
      
          int maxIdx = 0, maxVal = list[0];
          for (int idx = 1; idx < list.Count; ++idx) {
              // Higher or equal-and-to-the-right, replace.
      
              if (list[idx] >= maxVal) {
                  maxIdx = idx;
                  maxVal = list[idx];
              }
          }
          return maxIdx;
      }
      

      【讨论】:

        【解决方案4】:

        使用LastIndexOf

        int highestValue = someList.LastIndexOf(someList.Max());
        

        【讨论】:

        • 下注??请说明
        • 不是我,但如果我不得不猜测,我会说这是因为您的答案是之前发布的答案的直接副本。
        • @decPL 但是看看我发表评论的时间......关于我是第一个的问题:/
        • @decPL 我不知道为什么人们会无缘无故地写下...无论如何感谢 bud :)\
        猜你喜欢
        • 2015-10-21
        • 1970-01-01
        • 2017-04-09
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多