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);
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With