开发者

Converting decimal from LINQ query to Currency

Here is my LINQ Query:

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--^
    };

The it.Decimal is returning a decimal in the form 12345.00 and I need to convert that to $12,345.00 when displayed in the开发者_运维知识库 gridview. What I have now doesn't work, because a LINQ Query won't recognize the String.Format function. Any ideas?


Just remove the ToString:

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

You can also use this form:

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

If you pass it.Decimal.ToString() as a parameter to String.Format, it will be handled as a string, not a decimal, so it won't be able to apply the currency format.


EDIT: ok, so you have another problem... Don't forget that a Linq to SQL (or Entity Framework) query is converted to SQL and executed by the database; the database doesn't know String.Format, so it can't be converted to SQL. You need to retrieve the "raw" result from the db, and then format it using 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")
    };

(Note the use of AsEnumerable to "switch" to Linq to Objects)

Another option would be to give the raw decimal value to the GridView, and set the column's DataFormatString property to "C"


Can you just use the ToString() function to convert it to currency like this:

.ToString("c")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜