user3052918
user3052918

Reputation:

Convert string to int for sum in linq

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

Answers (4)

Kamil Budziewski
Kamil Budziewski

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

Felipe Oriani
Felipe Oriani

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

user1666620
user1666620

Reputation: 4808

have you tried using the int.TryParse?

Upvotes: 0

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

int? sum = q.Sum(g => Int32.Parse(g.requestAmount));

Upvotes: 3

Related Questions