2014-01-09 10 views
7

汎用コレクションの値を集計しようとしていますが、このコードを他のコードでも実行するのに同じ正確なコードを使用していますが、 ulongデータ型?LINQでのsumメソッドの使用

コード

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

答えて

16

Sum()ulongを返す過負荷を持っていない、とコンパイラが行うのオーバーロードのどちらを決定することはできません呼び出すために存在する。

あなたはそれがキャストで決めることができます:

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

私はちょうどすべてのulongsを10進数に変更しました。私はタイマーが立ち上がるとすぐにこれを受け入れます。 – lakedoo

+1

@lakedoo: 'Value'の型を変更すると、キャストは必要ありません。また、代わりに 'long'を望んでいないと確信していますか? – SLaks

+0

良い点、ええ私はそれに何か問題があるようにはそれほど長くないつもりです。再度、感謝します! – lakedoo

8

が合意についてSum()ulongを返す過負荷を持っていない、とコンパイラが判断できない呼び出すために存在しないオーバーロードのどの。

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

あなたはキャストを心配する必要はありません、それはネイティブ使用する方法を:あなたはにキャスト場合は、限り、あなたはその代わりに、あなたがこのような拡張メソッドを作成することができSystem.OverflowException: Arithmetic operation resulted in an overflow.

に実行することができますデータ型の追加。