Firstly this is my code:
int[] a = { 3, 2, 0, 4, -5, 8, 7, 6 };
Array.Sort(a);
for(int i = 0; i < a.Length; i )
{
Console.WriteLine(a[i]);
}
Output:
-5
0
2
3
4
6
7
8
My problem is that I want to sort all the numbers like the computer already does but except the -5. This is what I want the output to be:
0
2
3
4
-5
6
7
8
CodePudding user response:
You can do something like this :
using System.Linq;
int[] sorted = new [] { 3, 2, 0, 4, -5, 8, 7, 6 }.OrderBy(Math.Abs).ToArray();
// now you can print "sorted" as array
it will order items by their absolute values, which is what you are looking for.
CodePudding user response:
You can use code:
int[] a = { 3, 2, 0, 4, -5, 8, 7, 6 };
int[] result = a.OrderBy(a=> Math.Abs(a)).ToArray();
result: 0 , 2, 3, 4, -5, 6, 7, 8