Sort numbers with decimals that are stored in string

痴心易碎 提交于 2020-01-06 08:15:37

问题


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


回答1:


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;
        }
    }
}



回答2:


try

orderby(x=>double.Parse(x.Amount))




回答3:


This should work

var numberstring = "100.0,300.00,200.00,400.00";
var array = numberstring.Split(',');
var sortedstring = array.OrderBy(x => double.Parse(x)).Aggregate("", (current, val) => current + (val + ","));



回答4:


You can sort by the Length property which will provide the desired order. For example:

        IEnumerable<string> sizes = new List<string> { "200.00", "30.00", "56.36", "58888.00" };

        sizes = sizes.OrderBy(x => x.Length);



回答5:


You can do it in one line:

        var orderedAsString =
            amounts.Select(x => double.Parse(x.Amount) / 100)
                .OrderBy(x => x)
                .Select(x => x.ToString("0.00"));


来源:https://stackoverflow.com/questions/36746496/sort-numbers-with-decimals-that-are-stored-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!