【问题标题】:Using sum method in LINQ在 LINQ 中使用 sum 方法
【发布时间】:2014-01-09 18:56:41
【问题描述】:

我正在尝试总结 通用集合中的值,我在我的其他代码片段中使用了相同的确切代码来执行此功能,但它似乎有问题ulong 数据类型?

代码

   Items.Sum(e => e.Value); 

有以下错误:

错误 15 以下方法或属性之间的调用不明确:'System.Linq.Enumerable.Sum<System.Collections.Generic.KeyValuePair<int,ulong>>(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<int,ulong>>, System.Func<System.Collections.Generic.KeyValuePair<int,ulong>,float>)'和'System.Linq.Enumerable.Sum<System.Collections.Generic.KeyValuePair<int,ulong>>(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<int,ulong>>, System.Func<System.Collections.Generic.KeyValuePair<int,ulong>,decimal?>)

public class Teststuff : BaseContainer<int, ulong, ulong>
{
    public decimal CurrentTotal { get { return Items.Sum(e => e.Value); } }

    public override void Add(ulong item, int amount = 1)
    {
    }

    public override void Remove(ulong item, int amount = 1)
    {
    }
}

public abstract class BaseContainer<T, K, P>
{
    /// <summary>
    /// Pass in the owner of this container.
    /// </summary>
    public BaseContainer()
    {
        Items = new Dictionary<T, K>();
    }

    public BaseContainer()
    {
        Items = new Dictionary<T, K>();
    }

    public Dictionary<T, K> Items { get; private set; }
    public abstract void Add(P item, int amount = 1);
    public abstract void Remove(P item, int amount = 1);
}

【问题讨论】:

    标签: c# .net linq generics


    【解决方案1】:

    Sum() 没有返回 ulong 的重载,编译器无法决定调用哪些确实存在的重载。

    您可以通过演员表帮助它做出决定:

    Items.Sum(e => (decimal)e.Value)
    

    【讨论】:

    • 谢谢,我刚刚把所有的 ulong 都改成了十进制,我会在定时器到时立即接受。
    • @lakedoo:请注意,如果您更改Value 的类型,则不需要演员表。另外,您确定不想要long 吗?
    • 好点,是的,我会坚持很长时间,这似乎没有任何问题。再次感谢!
    • @lakedoo 小心溢出问题。将ulongs 加在一起并期待long 似乎很危险。要么你的属性一开始就不应该是ulong(如果他们确实需要那个精度,你的总和就会失败),或者你应该为Sum写一个扩展来处理ulong
    • @jb1t 的答案是最好的答案。它的风险更小(没有溢出异常)并且效率更高,因为它避免了列表中的每个项目
    【解决方案2】:

    同意Sum() 没有返回ulong 的重载,编译器无法决定调用哪些确实存在的重载。但是,如果你投到很长,你可能会遇到System.OverflowException: Arithmetic operation resulted in an overflow.

    相反,您可以创建这样的扩展方法:

    public static UInt64 Sum(this IEnumerable<UInt64> source)
    {
        return source.Aggregate((x, y) => x + y);
    }
    

    这样您就不必担心转换,它使用原生数据类型添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      相关资源
      最近更新 更多