开发者

How to convert a string to decimal in a LINQ query

开发者 https://www.devze.com 2023-03-20 09:01 出处:网络
I have the following Linq statement: var total = (from a in mobileChunk.Data select a.callCost).Sum();

I have the following Linq statement:

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

callCost is a string. I开发者_JAVA技巧 need to convert it to a decimal. How is this done?


i would do something like this....

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

now, in your linq.....

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


Perhaps you can try this:

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

精彩评论

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