×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

记得这里有几位LINQ大侠,来求助一下关于如何在LINQ里实现between。

现在需要filter某个字段按照给定的范围,用SQL如下:
select ProductType from Products
where ProductType between 'A' and 'C'
order by ProductType
网上找到一个BetweenExtensions(http://www.hookedonlinq.com/BetweenOperator.ashx),不能用,因为我需要的是N多个filters一起作用后的最终结果,
var query= from p in db.Products
joint xxx
select new { xxx, yyy, zzz ... }
if(...)
query=query.where(condition1);
if(...)
query=query.where(condition2);
if(...)
query=query.where(conditionN);

这样一层层把结果范围缩小,最后送给Gridview显示出来,所以返回结果必须是IQueryable类型,而BetweenExtension里的类型是IEnumerable,如果简单的把IEnumerable换成IQueryable,里面的iterator和IQueryable冲突。
Report

Replies, comments and Discussions:

  • 工作学习 / 学科技术讨论 / 记得这里有几位LINQ大侠,来求助一下关于如何在LINQ里实现between。
    现在需要filter某个字段按照给定的范围,用SQL如下:
    select ProductType from Products
    where ProductType between 'A' and 'C'
    order by ProductType
    网上找到一个BetweenExtensions(http://www.hookedonlinq.com/BetweenOperator.ashx),不能用,因为我需要的是N多个filters一起作用后的最终结果,
    var query= from p in db.Products
    joint xxx
    select new { xxx, yyy, zzz ... }
    if(...)
    query=query.where(condition1);
    if(...)
    query=query.where(condition2);
    if(...)
    query=query.where(conditionN);

    这样一层层把结果范围缩小,最后送给Gridview显示出来,所以返回结果必须是IQueryable类型,而BetweenExtension里的类型是IEnumerable,如果简单的把IEnumerable换成IQueryable,里面的iterator和IQueryable冲突。
    • How about using ProductType >= 'A' && ProductType <='C'
      • Operator '>=' cannot be applied to operands of type 'string' and 'char'
        • It’s just a prototype. Do I have to write out whole thing?
          query = query.where(p => p.ProductType.CompareTo(“A”) >=0 && p.ProductType.CompareTo(“C”) <=0);
          • Thanks a lot, it works perfect!
    • Actually you can directly use IEnumerable (base of IQueryable) as datasource of gridview.
      • Have you ever tried?
        if I define query like:
        IEnumerable query= from a in db.Products
        ......
        query.Where() query.Between() won't be seen
        only I use 'var' instead of 'IEnumerable' can solve this problem, but type 'var' will be dynamically assign into 'IQueryable<>' in run time
        • Of course you cannot use IEnumerable. You have to use IEnumerable<T>. It means you shouldn’t use anonymous query result. As matter factor, if you use anonymous query result, you’ll also have trouble to pass query result to other layer.
          • you reached the point, I had gotten some problem last time when I tried to pass the value of result between objects due to using anonymous query result. Thanks for your words.