Problem with Sum in c#
I开发者_如何学C'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?
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.
You need to explicitly convert the string to an int:
var ss=_someClassDataSource.Sum(s=> Convert.ToInt32(s.BreakdownCover));
As pointed out by DustinDavis Convert.ToInt32 will return a 0 if the string is null. If you would rather an exception be thrown then Int32.Parse will be a better option. However if the field accepts nulls and if these should be treated as 0 then this will return the expected result.
精彩评论