user1328639
user1328639

Reputation: 501

Sorting Nearest Numbers by using array

There is an array

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

and a number 8.

I wanna sort the array around 8 by nearest number.

the 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 this numbers. any idea?

Upvotes: 3

Views: 819

Answers (3)

payo
payo

Reputation: 4561

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 super fast, then SO stopped me with some captcha's asking if was human. Thanks a lot SO! :)

Upvotes: 1

Servy
Servy

Reputation: 203835

int nearbyNumber = 8;
var query = array.OrderBy(number => Math.Abs(number - nearbyNumber ));

You can call ToArray if you really need an array.

If you really want to sort the array in place you can make a custom Comparer object and use Array.Sort, but that's more work...

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460158

var result = array.OrderBy(i => Math.Abs(i - value))
             .ThenBy(i => i < value)
             .ToArray();

Upvotes: 4

Related Questions