Sort nearby numbers using an array

There is an array

int[] array = new int[]{6,4,10,7,7,9};

and number 8.

I want to sort an array around 8 by the closest number.

nearest numbers: 9,7,7,10,6,4 respectively

because 9-1 = 8, 7 + 1 = 8, 7 + 1 = 8, 10-2 = 8, 6 + 2 = 8, 4 + 4 = 8

how can i sort these numbers. any idea?

+3
source share
3 answers
var result = array.OrderBy(i => Math.Abs(i - value))
             .ThenBy(i => i < value)
             .ToArray();
+4
source
int nearbyNumber = 8;
var query = array.OrderBy(number => Math.Abs(number - nearbyNumber ));

You can call ToArrayif you really need an array.

If you really want to sort the array, you can create your own Comparer object and use Array.Sort, but this works more ...

+2
source
var array = new int[] { 6, 4, 10, 7, 7, 9 };
int target = 8;
var values = array.OrderBy(i => Math.Abs(i - target)).ToArray();

EDIT . I had this answer very quickly, then SO stopped me with some kind of cappuccino, asking if he was a man. Many thanks!:)

+1
source

All Articles