user3610374 user3610374 -3 years ago 103
C# Question

How to use linq to find the index of the item with the highest value

I know there is a related question here How do I get the index of the highest value in an array using LINQ? but it was asked 8 years ago so I'm asking if there is a newer/better version of that concept. Here is the code I have currently tried from that question:

var dataSelection = Data.Where(i => i.Date <= startingDate).Take(days);
highIndex = Data.FindIndex(dataSelection.Max(i => i.High);

(Doesn't work because FindIndex takes the class and not the item in the class

int maxIndex = -1;
int index=0;
double maxValue = 0;

int urgh = sequence.Select(value => {
if (maxIndex == -1 || value > maxValue)
maxIndex = index;
maxValue = value;
return maxIndex;

Update: I'm using a list of classes for the search and I'm trying to get the index of a class that has the highest value in a certain item in that class

Answer Source
var highIndex = Data.Select((v, i) => new{ Value = v, Index = i} ).OrderByDescending(x => x.Date).Select(x => x.Index).First();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download