Reputation: 10482
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?
Upvotes: 3
Views: 5528
Reputation: 38
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. :)
Upvotes: 2
Reputation: 55956
You can use Array.FindIndex
:
var n = Array.FindIndex(acc_avg, x => x > threshold);
Upvotes: 5