这是我的 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
的形式返回一个小数,当在 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/