評價: 2 回應: 2 閱覽: 132
置頂

LINQ問題

版上各位大神大家好

我想總結一個泛型集合

我已經有完成一段coding

但是執行時卻跑出ulong資料型態的error如下:

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

錯誤碼如下:

Error 15 The call is ambiguous between the following methods or properties: 

'System.Linq.Enumerable.Sum>(System.Collections.Generic.IEnumerable>, System.Func,float>)' and 'System.Linq.Enumerable.Sum>(System.Collections.Generic.IEnumerable>, System.Func,decimal?>)

coding程式碼如下: 

public class Teststuff : BaseContainer
{
    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
{
    /// 
    /// Pass in the owner of this container.
    /// 
    public BaseContainer()
    {
        Items = new Dictionary();
    }

    public BaseContainer()
    {
        Items = new Dictionary();
    }

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

請大大幫幫小弟

熱門回應

樓上說的正解!

不過你還是擔心最會發生易位問題

你可以把code嘗試改成這樣

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

 

乍看之下還以為是LINE軟體的LINEQ勒!

我來簡單回覆你的問題

Sum()並不具有overload ulong型別

編譯器不能確定你的資料哪些是要調用還是做單純呼叫

你可以試看看這樣寫

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

 

會員登入 (先登入會員才能回覆留言喔!)

Facebook留言