猿问

LINQ操作员之间

以下内容适用于IEnumerable类型,但是有什么方法可以针对sql数据库使用类似IQueryable的类型呢?


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;

   }

}


慕尼黑8549860
浏览 352回答 1
1回答

蝴蝶不菲

如果将其表示为where子句,则可以使用LINQ to SQL开箱即用,如果可以构造适当的表达式。就表达式树而言,可能有一种更好的方法-Marc Gravell可能会改进它-但值得一试。static class Ext{&nbsp; &nbsp;public static IQueryable<TSource> Between<TSource, TKey>&nbsp; &nbsp; &nbsp; &nbsp; (this IQueryable<TSource> source,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Expression<Func<TSource, TKey>> keySelector,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TKey low, TKey high) where TKey : IComparable<TKey>&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;Expression key = Expression.Invoke(keySelector,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keySelector.Parameters.ToArray());&nbsp; &nbsp; &nbsp; &nbsp;Expression lowerBound = Expression.GreaterThanOrEqual&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(key, Expression.Constant(low));&nbsp; &nbsp; &nbsp; &nbsp;Expression upperBound = Expression.LessThanOrEqual&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(key, Expression.Constant(high));&nbsp; &nbsp; &nbsp; &nbsp;Expression and = Expression.AndAlso(lowerBound, upperBound);&nbsp; &nbsp; &nbsp; &nbsp;Expression<Func<TSource, bool>> lambda =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Expression.Lambda<Func<TSource, bool>>(and, keySelector.Parameters);&nbsp; &nbsp; &nbsp; &nbsp;return source.Where(lambda);&nbsp; &nbsp;}}不过,这可能取决于所涉及的类型-特别是,我使用了比较运算符而不是IComparable<T>。我怀疑这更有可能正确地转换为SQL,但是您可以根据需要将其更改为使用该CompareTo方法。像这样调用它:var query = db.People.Between(person => person.Age, 18, 21);
随时随地看视频慕课网APP
我要回答