2

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?

2
  • 2
    it's nice to know that requestAmount is nvarchar(100), but as you're in an c# object world, you can just say that it's a string ;) Commented Dec 4, 2013 at 12:32
  • 2
    Enumerable.Sum never returns null. So are you sure you need a Nullable<int> ? Commented Dec 4, 2013 at 12:48

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Hmmm, and if requestAmount is null ?
@RaphaëlAlthaus there is no information about nullability of this field. If it's nullable nvarchar then we need to use Convert.ToInt32
Well, for your second version, sum whill never be null, so why use a Nullable<int>. Question is not clear on this point, you're right.
Anyway, Enumerable.Sum never returns null... So the second version is perfectly valid...
@RaphaëlAlthaus yeah, only way to return null will be making some if statement and checking if all values are null -> return null / else count sum of non-null values
3
int? sum = q.Sum(g => Int32.Parse(g.requestAmount));

Comments

2

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()));

Comments

0

have you tried using the int.TryParse?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.