简体   繁体   English

c#中的求和问题

[英]Problem with Sum in c#

I've got a LINQ query in VB: 我在VB中有一个LINQ查询:

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

where BreakdownCover 's type is string . BreakdownCover的类型是string When I'm trying rewrite it in C#: 当我尝试用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 使用Int.Parse,不要将字符串转换为int

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

If you're doing VB.NET then use 如果你正在做VB.NET然后使用

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

Here is why you can't cast string to int: 这就是为什么你不能将字符串转换为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... 因为未实现显式强制转换... ToString()是一种通用方法(在System.Object中实现),如果字符串将实现强制转换,如果所有其他类也需要实现它,那么它将提出问题...

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. 不使用Convert.ToInt32()可能会更好,因为当字符串为null时,Convert.ToInt32仍将返回一个值,而int.Parse将抛出该值。 You might get unexpected results with Convert.ToInt32. 使用Convert.ToInt32可能会得到意外的结果。 Also see this question Whats the main difference between int.Parse() and Convert.ToInt32 也看到这个问题是什么是int.Parse()和Convert.ToInt32之间的主要区别

Of course, this is based on the context as @Andy has pointed out. 当然,这是基于@Andy指出的背景。 If you are ok with NULL being treated as 0 then either method will work. 如果您将NULL视为0,那么任何一种方法都可以。

You need to explicitly convert the string to an int: 您需要将字符串显式转换为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. 正如DustinDavis Convert.ToInt32所指出的,如果字符串为null,则返回0。 If you would rather an exception be thrown then Int32.Parse will be a better option. 如果您希望抛出异常,那么Int32.Parse将是更好的选择。 However if the field accepts nulls and if these should be treated as 0 then this will return the expected result. 但是,如果该字段接受空值,并且如果这些值应被视为0,那么这将返回预期结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM