VladL
VladL

Reputation: 13033

Array get min value bigger than other value

I have following array:

float[] arr = { 0, 0.1f, 0, 0.1f, 0, 0.2f };

What is the most elegant way to select min value that is bigger than 0 or bigger than some other value?

I've tried using Min() and Select...From...OrderBy...First() but no luck until now.

Upvotes: 5

Views: 7528

Answers (4)

deerchao
deerchao

Reputation: 10544

All the current answers will get exceptions if all data is less than your "some other value". So, if that's not what you want, you will get null in this case with this code:

float[] arr = { 0, 0.1f, 0, 0.1f, 0, 0.2f };
var someOtherValue = 0;

var min = arr.Where(x => x > someOtherValue)
            .Cast<float?>()
            .Min();

Upvotes: 2

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

Try to use Where filter;

Filters a sequence of values based on a predicate.

And after use Min() method.

Returns the minimum value in a sequence of values.

arr.Where(a => a > 0).Min();

Here is is a DEMO.

Upvotes: 3

as-cii
as-cii

Reputation: 13019

You can exclude values using Where and then apply a Min:

array.Where(a => a > 1 && a < 10).Min();

Upvotes: 4

Rotem
Rotem

Reputation: 21917

Use the LINQ method Where to filter out zero values then use the LINQ method Min to retrieve the lowest value of the resulting collection.

arr.Where(f => f > 0).Min();

Upvotes: 22

Related Questions