Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c#, how to sort list of doubles by mantissa?

Tags:

c#

.net

linq

How to sort list of doubles by the fractional part of the double.
E.g: For input <1.2, 2.3, 1.12, 5.1>, after sorting, the output should be <5.1, 1.12, 1.2, 2.3>

like image 337
palindrome88 Avatar asked May 17 '17 03:05

palindrome88


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


1 Answers

You can achieve this through OrderBy() and Math.Truncate() method as like the following. Where x-Math.Truncate(x) gives you the number after the decimal point and OrderBy will arrange them in the ascending order. Have a look at this example and try yourself with 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 as well .OrderBy(x=>x-(int)x) instead for OrderBy(x=>x-Math.Truncate(x)

like image 153
sujith karivelil Avatar answered Oct 09 '22 20:10

sujith karivelil