Parsing dollar amounts
The NumberStyles
enumeration from System.Globalization
can be used to parse dollar amounts into decimals
:
decimal.Parse(r.Field<string>("Amount"), NumberStyles.Currency)
See also Problem parsing currency text to decimal type.
Summing dollar amounts
Also, your for-loop isn't actually adding any of the amounts, it's just assigning each amount to the a
variable, so that a
is only equal to the last amount at the end:
foreach (var item in query)
{
a = item.ToString();
}
return a;
What you really want to do is to add the amounts:
decimal a = 0;
foreach (var item in query)
{
a = a + item;
// Or even shorter:
a += item;
}
return a.ToString();
Summing with LINQ
But LINQ provides the method Sum()
which can be used to replace the for-loop altogether. Also, when Sum()
is called on an empty-set of decimals, it already returns 0
, so you don't need your if
block that checks if the count is 0
:
// Don't need this IF block
if (query.Count() == 0)
{
a = "0";
}
return query.Sum().ToString();
Altogther now...
So putting it all together, you get the code below:
// Top of file...
using System.Globalization;
// In your method...
var query =
from r in dt.AsEnumerable()
where r.Field<string>("Code") == strCode
select decimal.Parse(r.Field<string>("Amount"), NumberStyles.Currency);
return query.Sum().ToString();