How to convert a string to decimal in a LINQ query
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();
精彩评论