Why doesn't the following compile?
using System;
using System.Linq;
using System.Linq.Expressions;
public static class Extensions
{
public static V? SumOrDefault<T, V>(this IQueryable<T> @this, Expression<Func<T, V>> selector)
where V : struct, IComparable, IComparable<V>, IConvertible, IEquatable<V>, IFormattable
{
Expression<Func<T, V?>> nullableSelector = null; // omitted for brevity
return Queryable.Sum<T>(@this, nullableSelector);
}
}
It gives this error:
error CS1503: Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<T, V?>>' to 'System.Linq.Expressions.Expression<System.Func<T, decimal>>'
Two questions:
decimal
version of Sum<>
?decimal?
version of that function in System.Linq.Queryable
? public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, decimal?>> selector);
If that worked, technically, you could call that SumOrDefault
function with something that decimal cannot convert yet still respect your where
(
a custom "unsummable" class would, for example).string
And it can't find the decimal?
version of the function because it doesn't know which type to convert to safely.
C# doesn't have a way to filter a type to just numerics, AFAIK, so you will have to overload them manually like it's 2001:
public static decimal? SumOrDefault<T>(this IQueryable<T> @this, Expression<Func<T, decimal>> selector)
public static double? SumOrDefault<T>(this IQueryable<T> @this, Expression<Func<T, double>> selector)
//etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.