Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sum method in LINQ

I am trying to sum up the values in a generic collection, I have used the same exact code to perform the this function in other pieces of my code but it seems to have an issue with the ulong data type?

The code

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

has the following error:

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);
}
like image 719
lakedoo Avatar asked Jan 09 '14 18:01

lakedoo


1 Answers

Sum() has no overload that returns a ulong, and the compiler can't decide which of the overloads that do exist to call.

You can help it decide with a cast:

Items.Sum(e => (decimal)e.Value)
like image 71
SLaks Avatar answered Sep 21 '22 13:09

SLaks