简体   繁体   中英

Get value and index first low value in array

I need to find the three smallest values in an array, and keep track of their indices. But in my code I see only the index. Do you have any suggestions on how to fix this?

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);
    }
}
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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM