Matthew Goulart - 19 days ago 7x

Vb.net Question

Say we have a list of numbers:

`{1,3,7,13,19,54}`

and a single value :

`17`

What is the least expensive way to find the closest 2 numbers

`13`

`19`

Currently, I am using a loop to make 2 lists, one of numbers above and one of numbers below. Then I use something like this:

`point1 = pointsAbove.Aggregate(Function(x, y) If(Math.Abs(x.X - xVal) < Math.Abs(y.X - xVal), x, y))`

point2 = pointsBelow.Aggregate(Function(x, y) If(Math.Abs(x.X - xVal) < Math.Abs(y.X - xVal), x, y))

This seems so clunky to me. So I look to you!

Answer

Try the code below:

```
List<int> numbers = new List<int>(){ 6, 7, 8, 9, 1, 2, 3, 4, 5 };
int middle = 6;
var min = numbers.Where(y => y < middle).Max(); // min = 5
var max = numbers.Where(y => y > middle).Min(); // max = 7
```

The code above will work fine for sorted and unsorted lists.

If you can't be certain that you have at least one min and/or one max value, you must do this, otherwise you'll get an Exception:

```
var min = numbers.Where(y => y < middle).DefaultIfEmpty().Max();
var max = numbers.Where(y => y > middle).DefaultIfEmpty().Min();
```

And, in the case you are sure 100% of the time that the list is sorted, you can save a bit of performance doing the code below:

```
var min = numbers.LastOrDefault(y => y < middle);
var max = numbers.FirstOrDefault(y => y > middle);
```

I hope it helped you.

Source (Stackoverflow)

Comments