Aamir
Aamir

Reputation: 15576

Improve the LINQ query returning indexes of items meeting a certain condition

I have this LINQ query which returns the indexes of all the items in an array whose time value (which is a double) meets a certain condition as in the below query.

var sonicIndices = completeLog.Select((item, index) => new { Item = item, Index = index })
            .Where(x => Math.Abs(x.Item.time - nullValue) > 0.001)
            .Select(item => item.Index).ToArray();

I am pretty sure that this can be improved but how? I am stumped. Can anyone help me in this?

Upvotes: 3

Views: 279

Answers (2)

Andrei
Andrei

Reputation: 56716

Not an improvement, but just another way to do the same thing:

var sonicIndices = Enumerable.Range(0, completeLog.Length)
                   .Where(i => Math.Abs(completeLog[i].time - nullValue) > 0.001)
                   .ToArray();

Upvotes: 3

jlew
jlew

Reputation: 10601

I don't see anything particularly wrong with that, in what way does it need to be better? If you want a reusable method for this kind of thing, see: Getting a collection of index values using a LINQ query

Upvotes: 5

Related Questions