0

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

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

ToList call is redundant
To be honest, this line of code is neat and does the trick, but does whacking a few LINQ statements out like that really help the OP? You could include some helpful links which describe the LINQ keywords, and/or show him an old fashioned way as well for comparison.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.