LINQ操作员之间

编程入门 行业动态 更新时间:2024-10-23 10:28:36
本文介绍了LINQ操作员之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下对于IEnumerable类型可以很好地工作,但是有什么方法可以针对SQL数据库使用类似IQueryable的类型呢?

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 to 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<T>.我怀疑这更可能正确地转换为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操作员之间

本文发布于:2023-11-23 20:57:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作员   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!