以下适用于IEnumerable类型,但有没有办法得到这样的东西使用IQueryable类型对sql数据库?
class Program
{
static void Main(string[] args)
{
var items = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
foreach (var item in items.Where(i => i.Between(2, 6)))
Console.WriteLine(item);
}
}
static class Ext
{
public static bool Between<T>(this T source, T low, T high) where T : IComparable
{
return source.CompareTo(low) >= 0 && source.CompareTo(high) <= 0;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 47
如果你把它表达为一个where子句,它可以只使用LINQ to SQL开箱即用,如果你可以构造一个合适的表达式.
在表达树方面可能有更好的方法 - 马克格拉维尔可能能够改善它 - 但值得一试.
static class Ext
{
public static IQueryable<TSource> Between<TSource, TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
TKey low, TKey high) where TKey : IComparable<TKey>
{
Expression key = Expression.Invoke(keySelector,
keySelector.Parameters.ToArray());
Expression lowerBound = Expression.GreaterThanOrEqual
(key, Expression.Constant(low));
Expression upperBound = Expression.LessThanOrEqual
(key, Expression.Constant(high));
Expression and = Expression.AndAlso(lowerBound, upperBound);
Expression<Func<TSource, bool>> lambda =
Expression.Lambda<Func<TSource, bool>>(and, keySelector.Parameters);
return source.Where(lambda);
}
}
Run Code Online (Sandbox Code Playgroud)
它可能取决于所涉及的类型 - 特别是,我使用了比较运算符而不是IComparable<T>.我怀疑这更有可能被正确地翻译成SQL,但CompareTo如果你愿意,你可以改变它以使用该方法.
像这样调用它:
var query = db.People.Between(person => person.Age, 18, 21);
Run Code Online (Sandbox Code Playgroud)