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?

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67

4 Answers4

5

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

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
3
int? sum = q.Sum(g => Int32.Parse(g.requestAmount));
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
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()));
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
0

have you tried using the int.TryParse?

user1666620
  • 4,800
  • 18
  • 27