Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Sum in c#

I've got a LINQ query in VB:

Dim ss = _someClassDataSource.Sum(Function(s) TryCast(s, SomeClass).BreakdownCover)

where BreakdownCover's type is string. When I'm trying rewrite it in C#:

var ss = _someClassDataSource.Sum(s=>s.BreakdownCover);

I get the exception:

Cannot implicitly convert type 'string' to 'int'

How can I deal with this problem?

like image 624
user278618 Avatar asked Jul 26 '26 16:07

user278618


1 Answers

use Int.Parse, don't cast a string to an int

var ss=_someClassDataSource.Sum(s=>int.Parse(s.BreakdownCover));

If you're doing VB.NET then use

var ss=_someClassDataSource.Sum(s=>Integer.Parse(s.BreakdownCover));

Here is why you can't cast string to int:

Because the explicit cast isn't implemented... ToString() is a general method (implemented in System.Object) and if string would implement the cast that would beg the question if all other classes need to implement it too...

It would potentially be better to not use Convert.ToInt32() because Convert.ToInt32 will still return a value when the string is null while int.Parse will throw. You might get unexpected results with Convert.ToInt32. Also see this question Whats the main difference between int.Parse() and Convert.ToInt32

Of course, this is based on the context as @Andy has pointed out. If you are ok with NULL being treated as 0 then either method will work.

like image 66
Dustin Davis Avatar answered Jul 28 '26 07:07

Dustin Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!