【发布时间】:2009-01-20 19:23:04
【问题描述】:
我有一个双精度数组,我想要最大值的索引。这些是我迄今为止提出的解决方案,但我认为必须有一个更优雅的解决方案。想法?
double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 };
int topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderByDescending(x => x.Item).Select(x => x.Index).First();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderBy(x => x.Item).Select(x => x.Index).Last();
double maxVal = score.Max();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).Where(x => x.Item == maxVal).Select(x => x.Index).Single();
【问题讨论】:
-
我想知道人们在搜索这个问题时是否真的在寻找这个?
System.Array.IndexOf(score, score.Max())刚刚看到一个 Unity 开发人员使用下面的 LINQ 代码来完成这个简单的任务,我当时就在摸脸。