【问题标题】:Converting decimal from LINQ query to Currency将十进制从 LINQ 查询转换为货币
【发布时间】:2011-09-25 12:39:07
【问题描述】:

这是我的 LINQ 查询:

GridView.DataSource = from it in DataContext.Items
    where it.ThingId == thing.ThingId
    select new
    {
        it.Something,
        it.SomethingElse,
        it.AnotherSomething,
        Currency = String.Format("{0:C}", it.Decimal.ToString()), 
        //^--This is the line that needs to be converted to currency, this doesn't work--^
    };

it.Decimal 以12345.00 的形式返回一个小数,当显示在网格视图中时,我需要将其转换为$12,345.00。我现在所拥有的不起作用,因为 LINQ 查询无法识别 String.Format 函数。有什么想法吗?

【问题讨论】:

    标签: c# asp.net linq gridview


    【解决方案1】:

    只需删除ToString:

    Currency = String.Format("{0:C}", it.Decimal)
    

    您也可以使用这种形式:

    Currency = it.Decimal.ToString("C")
    

    如果您将it.Decimal.ToString() 作为参数传递给String.Format,它将被处理为字符串,而不是小数,因此无法应用货币格式。


    编辑:好的,所以你有另一个问题......不要忘记 Linq to SQL(或实体框架)查询被转换为 SQL 并由数据库执行;数据库不知道String.Format,所以无法转换成SQL。您需要从数据库中检索“原始”结果,然后使用 Linq to Objects 对其进行格式化:

    var query = from it in DataContext.Items
        where it.ThingId == thing.ThingId
        select new
        {
            it.Something,
            it.SomethingElse,
            it.AnotherSomething,
            it.Decimal
        };
    
    GridView.DataSource = from it in query.AsEnumerable()
        select new
        {
            it.Something,
            it.SomethingElse,
            it.AnotherSomething,
            Currency = it.Decimal.ToString("C")
        };
    

    (注意使用AsEnumerable“切换”到Linq to Objects)

    另一种选择是将原始十进制值赋予GridView,并将列的DataFormatString 属性设置为“C”

    【讨论】:

    • 当我去数据绑定时,我得到这个错误LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object)' method, and this method cannot be translated into a store expression.
    • @Chris 我收到一个错误:No overload for method 'ToString' takes 1 arguments
    • 完美运行!谢谢!根据我上面的代码,我认为这意味着您无法在 LINQ 查询中执行方法。我明白这一点,这就是为什么我需要一个替代方案。而你的作品完美!非常感谢!
    【解决方案2】:

    您可以像这样使用 ToString() 函数将其转换为货币吗:

    .ToString("c")
    

    【讨论】:

    • 当我环顾互联网时,我已经看到了这一点以及我正在做的事情,但由于某种原因,这会导致错误。显然我不应该给出 .ToString() 和参数?
    • 有趣。我不知道是什么原因造成的。您可以在 Linq 中将其保留为十进制,然后在显示时对其进行格式化。我知道这可能不是您要寻找的,但是很难说出那里可能存在什么问题。我已经这样做了,没有问题。
    • 对不起...我没有澄清...我正在尝试完成此操作,以便我可以回家...您不能在 LINQ 查询中执行此类操作...我认为这是我问题中的代码所暗示的。我猜不会。不过谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多