c# - 在 LINQ 中使用求和方法

标签 c# .net linq generics

我正在尝试对一个通用集合中的值求和,我在我的代码的其他部分中使用了完全相同的代码来执行此功能,但它似乎与ulong数据类型?

代码

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

出现以下错误:

Error 15 The call is ambiguous between the following methods or properties: '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>)' and '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);
}

最佳答案

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

您可以通过强制转换帮助它做出决定:

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

关于c# - 在 LINQ 中使用求和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21028785/

相关文章:

c# - Json 中的键和值

c# - EF 竞争 SaveChanges() 调用

c# - REST-Api 不工作 ControllerBase - 404 错误(C# .Net Core)

.net - 在网络服务器上管理多个.Net框架

c# - 使用 linq 删除列表中的重复项

c# - 运行 WPF 应用程序的 ClickOnce 部署版本时出现奇怪的行为

c# - 引用分配和读取是原子操作吗?

c# - 将原始 XML 绑定(bind)到 WPF 中的数据网格

c# - 无法通过 Magento API 更新库存可用性/库存值(value)

c# - 为什么 IEnumerable.Where 方法允许可以更改数据的谓词?