c# - 将小数从 LINQ 查询转换为货币

标签 c# asp.net linq gridview

这是我的 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.Decimal12345.00 的形式返回一个小数,当在 gridview 中显示时,我需要将其转换为 $12,345.00。我现在所拥有的不起作用,因为 LINQ 查询无法识别 String.Format 函数。有什么想法吗?

最佳答案

只需删除 ToString:

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

您也可以使用这种形式:

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

如果将it.Decimal.ToString()作为参数传递给String.Format,它将被作为字符串处理,而不是小数,所以它赢了'能够应用货币格式。


编辑:好的,所以你还有另一个问题......不要忘记 Linq to SQL(或 Entity Framework )查询被转换为 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”

关于c# - 将小数从 LINQ 查询转换为货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527439/

相关文章:

c# - 使用 linq 删除代码时出错

c# - 使用 SqlDataSource 时向 DropDownList 项目添加除值之外的属性

c# - 尝试 Response.Redirect 的正确方法是什么?

asp.net - asp.net cookie,身份验证和 session 超时

c# - 无需 PredicateBuilder 将动态谓词添加到表达式

c# - 检查,任何 LinqToSql 操作后操作成功

c# - SqlCommand 参数与 String.Format

c# - 使用键盘快捷键显示/隐藏 .NET 应用程序的最佳方式?

c# - LINQ - 仅针对最新记录的多个左外连接

c# - 动态 Linq 按变量排序