在LINQ中使用sum方法

时间:2014-01-09 18:56:42

标签: c# .net linq generics

我正在尝试总结泛型集合中的值,我使用相同的确切代码在我的代码的其他部分中执行此函数但它似乎有一个问题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);
}

2 个答案:

答案 0 :(得分:17)

Sum()没有返回ulong的重载,并且编译器无法确定哪些重载可以调用。

你可以通过演员来帮助它决定:

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

答案 1 :(得分:9)

同意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);
}

这样您就不必担心投射,并且它使用原生数据类型添加。