Reputation:
I have a column requestAmount
that is nvarchar(100)
.
I need to calculate sum :
int? sum = q.Sum(g => g.requestAmount);
I got this error:
Error 26 Cannot convert lambda expression to delegate type '
System.Func<samtaApplication.DbLayer.tblMaterial,int>
' because some of the return types in the block are not implicitly convertible to the delegate return type
How can I convert string to int?
Upvotes: 2
Views: 16298
Reputation: 23087
In linq to entities you can always materialize query first, so you will operate on linq to objects
int? sum = q.AsEnumerable().Sum(g => Int.Parse(g.requestAmount));
Note that it will load whole q
from db
EDIT:
if requestAmount
is nullable then use:
int? sum = q.AsEnumerable().Sum(g => Convert.ToInt32(g.requestAmount));
Convert.ToInt32
will return 0 when null is passed as parameter
Upvotes: 4
Reputation: 38608
A string
can be null or empty, so, keep it safe using a filter with Where
and after it applying and Sum
, for sample:
int dummy;
int result = q.Where(g => int.TryParse(g.TryParse(g.requestAmount, out dummy))
.Sum(g => int.Parse(g.requestAmount.Trim()));
Upvotes: 2
Reputation: 18411
int? sum = q.Sum(g => Int32.Parse(g.requestAmount));
Upvotes: 3