In C #, how to sort the mantissa doubling list?

How to sort the doubling list by the fractional part of a double.
For example: to enter <1.2, 2.3, 1.12, 5.1> after sorting, the output should be <5.1, 1.12, 1.2, 2.3>

+5
source share
3 answers

This can be done using OrderBy() and Math.Truncate() as Math.Truncate() below. Where x-Math.Truncate(x) gives you the number after the decimal point, and OrderBy arrange them in ascending order. Take a look at this example and try the following snippet

  List<double> input = new List<double>(){1.2, 2.3, 1.12, 5.1}; input = input.OrderBy(x=>x-Math.Truncate(x)).ToList(); Console.WriteLine(String.Join("\n",input)); 

Or you can try this .OrderBy(x=>x-(int)x) instead for OrderBy(x=>x-Math.Truncate(x)

+11
source

List has an overload of the Sort() method, which accepts an instance of IComparer<T> . the interface is quite simple to implement and will allow you to sort in any way you want:

 public class MantissaComparer : IComparer<double> { public int Compare(double x, double y) { return Comparer<double>.Default.Compare(x - Math.Truncate(x), y - Math.Truncate(y)); } } 

Then use a custom comparator as follows:

 input.Sort(new MantissaComparer()); 

I see the linq tag, but this solution is used more than once in the whole code if you deem it necessary, while avoiding over-engineering due to the simple IComparer interface.

+1
source

You can also try below without using Math.Truncate

 var sortedlist = list.OrderBy(n => n - (int)n).ToList(); Console.Write(String.Join(",", sortedlist)); 
+1
source

All Articles