Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding index from Select query in Linq

Tags:

c#

linq

I'm trying to find the index at which the difference between two properties in a List<> is max? Currently, I'm finding the max using this LINQ query below:

var result = link.Select(x => Math.Abs(x.Prop1 - x.Prop2)).Max();

How can I get the index ?

like image 285
hello Avatar asked Sep 03 '25 09:09

hello


2 Answers

var result = 
     link.Select((x, i) => new { value = Math.Abs(x.Prop1 - x.Prop2), index = i })
          .OrderByDescending(x=>x.value)
          .FirstOrDefault();

var indexValue = result?.index;
var maxValue = result?.value;

Here this is working.

like image 140
mybirthname Avatar answered Sep 04 '25 23:09

mybirthname


If you have a large amount of data, you might get concerned about those methods creating 2 extra sets of data before you get the result. You could use a from statement and generate only one extra set:

int index = (from i in Enumerable.Range(0, link.Count)
             orderby Math.Abs(link.Prop1 - link.Prop2)
             select new { index = i, value = link[i] }).First().index;

Or use a plain for loop and not create any extra sets:

int max = 0;
int indx = 0;
for(int i = 0; i < link.Count;i++)
{
    int temp = Math.Abs(link.Prop1 - link.Prop2);
    if (temp > max)
    {
        max = temp;
        indx = i;
    }
}
like image 31
tinstaafl Avatar answered Sep 05 '25 00:09

tinstaafl