Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting index of array that has a value larger than a threshold

Tags:

c#

linq

I have an array of doubles and a threshold value. I would like to select the first index in my array where the value at the index is larger than the threshold.

How the do I accomplish that in LINQ?

I got it to work with:

var n = acc_avg.Select((val, index) => new {Val = val, Index = index})
               .Where(l => l.Val > threshold)
               .First()
               .Index

But is there is better way?

like image 742
kasperhj Avatar asked Nov 29 '25 20:11

kasperhj


2 Answers

You can use Array.FindIndex:

var n = Array.FindIndex(acc_avg, x => x > threshold);
like image 168
Paolo Moretti Avatar answered Dec 02 '25 08:12

Paolo Moretti


Your solution looks pretty decent to me, but I believe it will throw an exception if there are no elements in the sequence that meet your criteria. I'd consider FirstOrDefault instead of First and test for null before accessing.

var n = acc_avg.Select((val,index) => new {Val= val, Index = index}).Where(l=> l.Val > threshold).FirstOrDefault();    
if(n != null)
  DoSomething(n.Index);

Of course, if your object already had an index property (or if the location in the sequence isn't important to you) you could shorten this to:

var n = acc_avg.FirstOrDefault(l => l > threshold);  

But you probably knew that. :)

like image 39
Kevin Walsh Avatar answered Dec 02 '25 08:12

Kevin Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!