Search code examples
c#.netlinqsortingstable-sort

Sort numbers with decimals that are stored in string


I have numbers that are getting converted to string. for example I have an amount 20000 and I have to show it as 200.00 so I am performing

string Amount = $"{Convert.ToDouble(x.Amount) / 100:0.00}"     

and then I store them to list of amounts with values

200.00, 30.00, 588888.00, 56.36,

I tried sorting it by orderby(x=>x.Anount) but this sorts on basis of string with first number as

200.00, 30.00, 56.36, 58888.00

I want the output to be sorted as

30.00, 56.36, 200.00, 588888.00


Solution

  • Pass a custom comparer into OrderBy. Enumerable.OrderBy will let you specify any comparer you like.

    void Main()
    {
        string[] decimals = new string[] { "30.00", "56.36", "200.00", "588888.00" };
    
        foreach (var dec in decimals.OrderBy(x => x, new DecimalComparer()))
        {    
            Console.WriteLine(thing);
        }
    }
    
    
    public class DecimalComparer: IComparer<string>
    {
        public int Compare(string s1, string s2)
        {
            if (IsDecimal(s1) && IsDecimal(s2))
            {
                if (Convert.ToDecimal(s1) > Convert.ToDecimal(s2)) return 1;
                if (Convert.ToDecimal(s1) < Convert.ToDecimal(s2)) return -1;
                if (Convert.ToDecimal(s1) == Convert.ToDecimal(s2)) return 0;
            }
    
            if (IsDecimal(s1) && !IsDecimal(s2))
                return -1;
    
            if (!IsDecimal(s1) && IsDecimal(s2))
                return 1;
    
            return string.Compare(s1, s2, true);
        }
    
        public static bool IsDecimal(object value)
        {
            try {
                int i = Convert.ToDecimal(value.ToString());
                return true; 
            }
            catch (FormatException) {
                return false;
            }
        }
    }