Reputation: 451
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);
}
}
Upvotes: 0
Views: 115
Reputation: 17279
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)
}
Upvotes: 3