获取数组中的值和索引第一个低值

时间:2013-12-15 20:30:09

标签: c# linq

我需要找到数组中的三个最小值,并跟踪它们的索引。但在我的代码中,我看到索引。您对如何解决此问题有任何建议吗?

static void Main()
{
    int[] array = new int[] { 4, -2, 17, 8, -3, 7, 0, 1, 5, -12, -11, -4, 9 };
    var topThree = array.OrderBy(i => i).Take(3).ToArray();
    var topThreeIndex = array.Select((v, i) => new { Index = i, Value = v })
                    .Where(p => Array.IndexOf(topThree, (int)p.Value) != -1)
                    .Select(p => p.Index);
    foreach (var x in topThreeIndex)
    {
        Console.WriteLine("The number is :"+??+" , index is: "+x);
    }
}

1 个答案:

答案 0 :(得分:3)

var topThreeIndex = array.Select((v, i) => new { Index = i, Value = v })
                         .OrderBy(e => e.Value)
                         .Take(3);

foreach (var x in topThreeIndex)
{
    Console.WriteLine("The number is: " + x.Value + " , index is: " + x.Index)
}