操作员之间的 LINQ

编程入门 行业动态 更新时间:2024-10-23 14:24:27
本文介绍了操作员之间的 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

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

发布评论

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

>www.elefans.com

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