Queryable.Aggregate 不适用于空值

Queryable.Aggregate is not working with null values

我正在编写一个可以转换 IQueryable 查询的访问者。它使用带有种子 nullAggregate 方法,然后使用一些函数对其进行转换。我的问题是这个 null 的类型是 decimal?。但是我得到一个例外

'Expression of type 'System.Object' cannot be used for parameter of type 
'System.Nullable`1[System.Decimal]' of method 'System.Nullable`1[System.Decimal] 
Aggregate[Nullable`1,Nullable`1]
(System.Linq.IQueryable`1[System.Nullable`1[System.Decimal]], 
System.Nullable`1[System.Decimal], 
System.Linq.Expressions.Expression`1[System.Func`3[System.Nullable`1[System.Decimal],
System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]]])''

经过一些研究,我发现是 Aggregate 本身破坏了我的查询:

public static TAccumulate Aggregate<TSource,TAccumulate>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func) {
    if (source == null)
        throw Error.ArgumentNull("source");
    if (func == null)
        throw Error.ArgumentNull("func");
    return source.Provider.Execute<TAccumulate>(
        Expression.Call(
            null,
            GetMethodInfo(Queryable.Aggregate, source, seed, func),
            new Expression[] { source.Expression, Expression.Constant(seed), Expression.Quote(func) }
            ));
}

我的问题是 Expression.Constant(seed),它是 null 并且 Expression.Constant 将其转换为对象类型的常量:

public static ConstantExpression Constant(object value) {
    return ConstantExpression.Make(value, value == null ? typeof(object) : value.GetType());
}

因此我的 new decimal?() 变成了 (object) null,我得到了这个错误。

有什么解决方法吗?似乎无法在 .net 框架中修复(即使可能,也会在 4.7 或更高版本中修复)。我为此创建了一个拉取请求,但我确定它不会被接受。

要重现的代码片段:

var result = new int?[] {1}.AsQueryable().Aggregate(default(int?), (a, b) => b);

这个怎么样:

public static TAccumulate Aggregate<TSource,TAccumulate>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func) {
    if (source == null)
        throw Error.ArgumentNull("source");
    if (func == null)
        throw Error.ArgumentNull("func");
    return source.Provider.Execute<TAccumulate>(
        Expression.Call(
            null,
            GetMethodInfo(Queryable.Aggregate, source, seed, func),
            new Expression[] { source.Expression, Expression.Constant(seed, typeof(TAccumulate)), Expression.Quote(func) }
            ));
}

从代码片段开始重现

var result = new int?[] {1}.AsQueryable().Aggregate(default(int?), (a, b) => b);

我会把它改成

var result2 = new int?[] {1}.AsQueryable().DefaultIfEmpty().Aggregate((a, b) => b);

如果你想要等值的金额

集合为空

var result3 = new int?[0].AsQueryable().DefaultIfEmpty().Aggregate(
   (a, b) => a.GetValueOrDefault() + b.GetValueOrDefault());

包含 null

var result4 = new int?[]{1,2,null}.AsQueryable().DefaultIfEmpty().Aggregate(
 (a, b) => a.GetValueOrDefault() + b.GetValueOrDefault());

基本上,我建议使用 DefaultIfEmpty().Aggregate