用存储在字符串中的小数对数字进行排序 [英] Sort numbers with decimals that are stored in string

查看:120
本文介绍了用存储在字符串中的小数对数字进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数字将转换为字符串. 例如,我有20000的金额,我必须将其显示为200.00,所以我正在执行

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,

200.00, 30.00, 588888.00, 56.36,

我尝试按orderby(x=>x.Anount)对其进行排序,但这是根据第一个数字为

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

200.00, 30.00, 56.36, 58888.00

我希望将输出排序为

30.00, 56.36, 200.00, 588888.00

30.00, 56.36, 200.00, 588888.00

推荐答案

将自定义比较器传递到OrderBy. Enumerable.OrderBy 可让您指定所需的任何比较器.

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

这篇关于用存储在字符串中的小数对数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆