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 ?
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With