从索引数组中获取前3个最高值

时间:2018-06-04 18:35:47

标签: c# linq

我有一个包含双打的数组。现在我想从数组中获取3个最高值,我想知道它们的索引是什么。

这是我的代码:

var threeHighest = wineOfferCounter.OrderByDescending(x => x).Take(3).ToArray();
var firstIndex = wineOfferCounter.ToList().IndexOf(threeHighest[0]);
var secondIndex = wineOfferCounter.ToList().IndexOf(threeHighest[1]);
var thirdIndex = wineOfferCounter.ToList().IndexOf(threeHighest[2]);

Console.WriteLine("Offer " + firstIndex + " bought " + threeHighest[0] + " times");
Console.WriteLine("Offer " + secondIndex + " bought " + threeHighest[1] + " times");
Console.WriteLine("Offer " + thirdIndex + " bought " + threeHighest[2] + " times");

但是当wineOfferCounter包含两个或更多相同的值时,我得到第一个索引两次。相反,我想获得独特的索引。因此,如果位置wineOfferCounter[3]的值为25,则wineOfferCounter[6]的值也为25.结果为:

"Offer 3 bought 25 times"
"Offer 3 bought 25 times"

但我想:

"Offer 3 bought 25 times"
"Offer 6 bought 25 times"

2 个答案:

答案 0 :(得分:4)

您可以使用索引和值创建临时类,然后按此类成员进行排序。类似这样的代码:

var result = wineOfferCounter
    .Select((v, i) => new { v, i })
    .OrderByDescending(x => x.v)
    .ThenByDescending(x => x.i)
    .Take(3)
    .ToArray();

然后遍历此集合:

foreach (var entry in result)
{
    Console.WriteLine("Offer " + entry.i + " bought " + entry.v + " times");
}

答案 1 :(得分:1)

或者无需为此创建一个简单的类,您可以使用元组:

var threeHighest = wineOfferCounter
            .Select((offerTimes, index) => new Tuple<int, double>(index, offerTimes))
            .OrderByDescending(t => t.Item2)
            .Take(3)
            .ToArray();

foreach (var offer in threeHighest)
{
    Console.WriteLine("Offer " + offer.Item1 + " bought " + offer.Item2 + " times");
}