3

I have a Dictionary<int, double> and i want to custom sort it. But is it a little different sorting.

For example here is the codes:

Dictionary<int, double> dicZeroPeriods = new Dictionary<int, double>();
dicZeroPeriods.Add (80,-3.5);
dicZeroPeriods.Add (90,-2.4);
dicZeroPeriods.Add (50,4.2);
dicZeroPeriods.Add (65,1.2);

So how can i custom sort the dicZeroPeriods by value base near zero. I mean the result should be:

65,1.2
90,-2.4
80,-3.5
50,4.2
teo van kot
  • 12,350
  • 10
  • 38
  • 70
lotomax
  • 113
  • 2
  • 12
  • `Dictionary` don't have a sort method you may need to use `SortedDictionary` check this post [How to use custom IComparer for SortedDictionary?](http://stackoverflow.com/questions/2720009/how-to-use-custom-icomparer-for-sorteddictionary), or recreate the dictionary in sorted order – bansi Mar 01 '17 at 06:00
  • I can't use SortedDictionary because i have some same entries. – lotomax Mar 01 '17 at 06:02

2 Answers2

4

Just use OrderBy with Math.Abs function. Here you go:

dicZeroPeriods = dicZeroPeriods.OrderBy(x => Math.Abs(x.Value))
            .ToDictionary(x => x.Key, x => x.Value);
teo van kot
  • 12,350
  • 10
  • 38
  • 70
0

use Math.Abs() to sort your dictionary elements by its absolute values. Math.Abs(1.2) < Math.Abs(-3.5) and so on.

Gramin
  • 9
  • 5