如何在LINQ查询中将字符串转换为十进制

时间:2011-07-14 04:58:05

标签: linq

我有以下Linq声明:

var total = (from a in mobileChunk.Data select a.callCost).Sum();

callCost是一个字符串。我需要将其转换为小数。这是怎么做到的?

2 个答案:

答案 0 :(得分:4)

我会做这样的事......

public static class Extenders
{
    public static decimal ToDecimal(this string str)
    {
        // you can throw an exception or return a default value here
        if ( string.IsNullOrEmpty(str) ) 
          return someDefaultValue;

        decimal d ;

        // you could throw an exception or return a default value on failure
        if ( !decimal.TryParse(str, out d ) ) 
           return someDefaultValue; 

        return d;
    }
}

现在,在你的林肯......

var total = = (from a in mobileChunk.Data select a.callCost.ToDecimal()).Sum();

答案 1 :(得分:3)

也许你可以试试这个:

var total = (from a in mobileChunk.Data select decimal.Parse(a.callCost)).Sum();