0

Lets say we have input: var myList = new List<int>(){ 100, 85, -200, -75, 50 }

How would you sort this based on absolute values and get a sorted list based on the absolute values while still keeping the original values?

So the desired output would look like this: {-200, 100, 85, -75, 50}

I get that you can use Math.abs() to get the absolute values and then sort it, but i want to keep the original values. (Knowing whether it is a negative/positive is of importance.)

  • 3
    Does this answer your question? [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) ... and use `Math.Abs` in the expression instead of a property. – madreflection Apr 21 '20 at 06:44
  • 1
    `myList = myList.OrderByDescending(x => Math.Abs(x));` – mortb Apr 21 '20 at 06:49
  • Wow completetly oversaw this. didn't think it would be that easy, I was way overthinking it with something like a dictionary with keys where the original value could be retrieved from. Thanks so much. – Fatih Ertikin Apr 21 '20 at 06:52
  • You should also think about how you want to sort numbers that have the same absolute value. Like should it look like `-2, -2, 2, 2, 2`, `2, 2, 2, -2, -2` or just how it comes `-2, 2, 2 -2, 2` – Ackdari Apr 21 '20 at 06:53

0 Answers0