2011-06-29 82 views
1

这里是我的LINQ查询:从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函数。有任何想法吗?

回答

7

只需卸下ToString

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

您也可以使用这种形式:

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

如果传递it.Decimal.ToString()作为参数传递给String.Format,它将被作为一个字符串,而不是处理十进制,所以它将无法应用货币格式。


编辑:好了,你还有一个问题...不要忘记,LINQ到SQL(或实体框架)查询转换为SQL和数据库执行;数据库不知道String.Format,所以它不能转换为SQL。你需要从数据库中检索“原始”的结果,然后将它使用LINQ to对象格式:

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到对象)

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

+0

当我去databind,我得到这个错误'LINQ to Entities不能识别方法System.String Format(System.String,System.Object)'方法,并且这个方法不能被转换成存储表达式.' –

+0

然后使用第二种形式。 –

+0

@Jordan Foreman,看我更新的回答 –

0

可你只需要使用的ToString()函数将其转换为货币这样的:

.ToString("c") 
+0

我已经看到了这个以及我在浏览网页时看到的内容,但由于某种原因,这个错误会导致错误。显然我不应该给.ToString()和参数? –

+0

有趣。我不知道可能是什么原因造成的。您可以在Linq中将其保留为十进制,然后在显示时将其格式化。我知道这可能不是你想要的,但很难说出那里可能存在的问题。我已经做到了这一点,并没有问题。 – Narnian

+0

对不起......我没有澄清......我试图做到这一点,所以我可以回家......你不能在LINQ查询中这样做......我认为这是暗示的代码在我的问题。我猜不会。谢谢你! –