【问题标题】:Linq method Sum not supported in .NET 7 generic math?Linq method Sum not supported in .NET 7 generic math?
【发布时间】:2022-12-27 04:22:06
【问题描述】:

I have the following code, but it does not compile in Visual Studio 17.4 preview 2.1 and .NET 7 RC1 SDK:

using System.Numerics;

int averageInt = Average<int, int>(1, 5, 10);
Console.WriteLine(averageInt);

double averageDouble = Average<int, double>(1, 5, 10);
Console.WriteLine(averageDouble);

TResult Average<TInput, TResult>(params TInput[] numbers)
    where TInput : INumber<TInput>
    where TResult : INumber<TResult> => numbers.Sum() / TResult.CreateChecked(numbers.Length);

The compiler error I get is: Error CS1929 'TInput[]' does not contain a definition for 'Sum' and the best extension method overload 'Queryable.Sum(IQueryable&lt;decimal&gt;)' requires a receiver of type 'IQueryable&lt;decimal&gt;'

I tried the following as an alternative, but it also doesn't compile:

using System.Numerics;

int averageInt = Average<int, int>(1, 5, 10);
Console.WriteLine(averageInt);

double averageDouble = Average<int, double>(1, 5, 10);
Console.WriteLine(averageDouble);

TResult Average<TInput, TResult>(params TInput[] numbers)
    where TInput : INumber<TInput>
    where TResult : INumber<TResult> => numbers.AsQueryable().Sum() / TResult.CreateChecked(numbers.Length);

With the error: Error CS1929 'IQueryable&lt;TInput&gt;' does not contain a definition for 'Sum' and the best extension method overload 'Queryable.Sum(IQueryable&lt;decimal&gt;)' requires a receiver of type 'IQueryable&lt;decimal&gt;'

What am I missing here?

【问题讨论】:

标签: c# .net linq .net-7.0


【解决方案1】:

ATM there is no overload for Enumerable.Sum (as for Max, Min etc.) leveraging the generic math. For now you can work around using Enumerable.Aggregate:

TResult Average<TInput, TResult>(params TInput[] numbers)
    where TInput : INumber<TInput>
    where TResult : INumber<TResult> 
    => numbers.Aggregate(TResult.Zero, (agg, t) => agg + TResult.CreateChecked(t)) 
          / TResult.CreateChecked(numbers.Length);

The same approach can be used for other similar operations.

For build in support - monitor this github issue.

【讨论】:

    猜你喜欢
    • 2022-12-27
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2019-11-06
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多