Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot resolve method Sum

Tags:

c#

linq

Tried to reuse Sum but got this error:

cannot resolve method Sum

how can I change my syntax

   private static void AggregatesData(User user)
        {
            user.TotalActiveUsers = SumToolbarsData(user.bars,(tb => tb.ActiveUsers));

            user.TotalInstalls = SumToolbarsData(user.bars, (tb => tb.Installs));

            user.TotalBalance = SumToolbarsData(user.bars, (tb => tb.Balance));
        }

        private static T SumToolbarsData<T>(List<Bar> bars, Func<Bar, T> selector)
        {
            return bars.Sum<T>(selector);
        }
like image 415
Elad Benda Avatar asked Feb 14 '12 07:02

Elad Benda


1 Answers

LINQ does not provide, out of the box, a generic version of Sum, for the reason that the language and runtime (prior to dynamic) does not allow generic (<T>) values to be added; there is no INumber interface, and the language does not support operators (+) on generic types (<T>). Either switch to overloads that take Func<T, float>, Func<T, int>, etc - or use the MiscUtil library which does include a generic Sum<T> implementation, specifically:

public static TSource Sum<TSource>(this IEnumerable<TSource> source);
public static TValue Sum<TSource, TValue>(this IEnumerable<TSource> source,
                        Func<TSource,TValue> selector);

which it does by resolving the + operator, and using some smoke and mirrors (so that it isn't slow, etc).

like image 84
Marc Gravell Avatar answered Oct 05 '22 23:10

Marc Gravell