将LINQ查询中的十进制转换为货币

Jor*_*man 1 c# linq asp.net 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--^
    };
Run Code Online (Sandbox Code Playgroud)

it.Decimal被返回的形式小数12345.00,我需要将其转换成$12,345.00当在GridView显示.我现在所做的不起作用,因为LINQ查询无法识别该String.Format功能.有任何想法吗?

Tho*_*que 7

只需删除ToString:

Currency = String.Format("{0:C}", it.Decimal)
Run Code Online (Sandbox Code Playgroud)

您也可以使用此表单:

Currency = it.Decimal.ToString("C")
Run Code Online (Sandbox Code Playgroud)

如果it.Decimal.ToString()作为参数传递String.Format,它将作为字符串处理,而不是小数,因此它将无法应用货币格式.


编辑:好的,所以你有另一个问题...不要忘记Linq to SQL(或实体框架)查询转换为SQL并由数据库执行; 数据库不知道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")
    };
Run Code Online (Sandbox Code Playgroud)

(注意使用AsEnumerable"切换"到Linq到Objects)

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