操作员之间的 LINQ [英] LINQ Between Operator

查看:30
本文介绍了操作员之间的 LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下适用于 IEnumerable 类型,但是有什么方法可以使 IQueryable 类型与 sql 数据库一起使用?

The following works fine with IEnumerable types, but is there any way to get something like this working with IQueryable types against a sql database?

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;
   }
}

推荐答案

如果您将其表示为 where 子句,它可能就可以使用 LINQ 开箱即用SQL,如果你能构造一个合适的表达式.

If you express it as a where clause it may just work out of the box with LINQ to SQL, if you can construct an appropriate expression.

就表达式树而言,可能有更好的方法来做到这一点 - Marc Gravell 很可能能够改进它 - 但值得一试.

There may be a better way of doing this in terms of the expression trees - Marc Gravell may well be able to improve it - but it's worth a try.

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);
   }
}

这可能取决于所涉及的类型 - 特别是,我使用了比较运算符而不是 IComparable.我怀疑这更有可能被正确地转换为 SQL,但如果需要,您可以将其更改为使用 CompareTo 方法.

It will probably depend on the type involved though - in particular, I've used the comparison operators rather than IComparable<T>. I suspect this is more likely to be correctly translated into SQL, but you could change it to use the CompareTo method if you want.

像这样调用它:

var query = db.People.Between(person => person.Age, 18, 21);

这篇关于操作员之间的 LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆