这是我的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
函数。有什么想法吗?
答案 0 :(得分:7)
只需删除ToString
:
Currency = String.Format("{0:C}", it.Decimal)
您也可以使用此表单:
Currency = it.Decimal.ToString("C")
如果您将it.Decimal.ToString()
作为参数传递给String.Format
,则会将其作为字符串处理,而不是小数处理,因此无法应用货币格式。
String.Format
,因此无法转换为SQL。您需要从db检索“原始”结果,然后使用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”
答案 1 :(得分:0)
你能使用ToString()函数将其转换为这样的货币:
.ToString("c")