4

A newbie with C# and LINQ. I have an array which is essentially a counted sequence.

{1,3,5,2,7,2}

I am trying to write a query that returns list of indices with highest values in descending order:

4,2,1,3,5,0

I can get the maximum index with this query below, but I can't seem to work out how to get the next indexes in sequence with a single query.

int index = array.ToList().IndexOf(array.Max()); 
2
  • possible duplicate of Linq Orderby Descending Query Commented Aug 31, 2015 at 7:13
  • 2
    @OldFox - That's not a duplicate at all. Commented Aug 31, 2015 at 7:15

2 Answers 2

10

This works:

var list = new [] {1,3,5,2,7,2}; var indices = list .Select((n, i) => new { n, i }) .OrderByDescending(x => x.n) .Select(x => x.i) .ToArray(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Enigmativity!
@tarzan - If you like my answer don't forget to click the accept tick. :-)
5

You can use Select:-

var result = numbers.Select((v, i) => new { Value = v, Index = i }) .OrderByDescending(x => x.Value) .Select(x => x.Index).ToArray(); 

Working Fiddle.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.