如何使用扩展方法 Sum() 获取短裤列表的总和?
我试图做这样的事情 -
List<short> listofshorts= new List<short>();
int s = listofshorts.Sum();
//this does not work...but same code works for a list of ints..
我收到这个编译错误 -
“System.Collections.Generic.List”不包含“Sum”的定义,并且最佳扩展方法重载“System.Linq.Queryable.Sum(System.Linq.IQueryable)”具有一些无效参数
任何人都可以建议我如何才能使用扩展方法来计算短路之和?由于某种原因,扩展方法不支持它......
I was trying to do something like this -
List<short> listofshorts= new List<short>();
int s = listofshorts.Sum();
//this does not work...but same code works for a list of ints..
I got this compilation error -
'System.Collections.Generic.List' does not contain a definition for 'Sum' and the best extension method overload 'System.Linq.Queryable.Sum(System.Linq.IQueryable)' has some invalid arguments
Can anyone suggest how can I use an extension method to calculate the sum of shorts? For some reason the extension method does not support it ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以为该方法提供 lambda:
You can provide the lambda for the method:
为了后代的利益,并指出这个看似明显的解决方案不起作用 - 我将在这个答案中留下有关 .NET 3.5 SP1+ 行为的以下链接:
In the interest of posterity, and pointing out this seemingly obvious solution doesn't work - I'm going to leave this answer with the following links about .NET 3.5 SP1+ behavior:
你可以做
You could do
就像其他人所建议的那样,您需要将短对象转换为 Enumerable.Sum 方法。不幸的是,对于某些类型(如 ulong 等)没有重载的 Sum 方法。
如果您经常需要它,我建议您自己编写一个扩展方法,这是我不久前为 ulong 和 ulong 所做的一个扩展方法?,您可以做一些非常类似的简短操作或您需要的任何其他类型:
PS,在我纯粹出于好奇而查看了反射器之后,我的实现基于 Enumerable.Sum 实现:-P
Like the others have suggested, you will need to cast the short objects to a type which is supported by the Enumerable.Sum method. Unfortunately there are no overloaded Sum method for some of the types like ulong, etc.
If you're gonna be needing it very often though, I'd recommend writing an extension method yourself, here's one I did a while back for ulong and ulong?, you can do something very similar for short or any other types you need:
P.S. my implementations are based on the Enumerable.Sum implementation after I took a peek with reflector purely out of curiosity :-P
我可能会选择 .ForEach() 扩展名,这里不需要任何转换
I would probably chose the .ForEach() extension, you don't need any casting here