【问题标题】:Does LINQ to SQL support the t-sql "in" statementLINQ to SQL 是否支持 t-sql "in" 语句
【发布时间】:2010-11-20 23:29:24
【问题描述】:

我不知道如何更好地描述标题(所以请随意更改),但我想在 LINQ to SQL 中生成以下语句的等效项:

select * from products where category in ('shoes','boots')

这些字段本质上将来自查询字符串(比这更安全,但为了便于解释)即

string[] myfields = request.querystring["categories"].split(',');

谢谢

【问题讨论】:

    标签: c# linq linq-to-sql tsql


    【解决方案1】:

    是的,你使用Contains

    db.Products.Where(product => myFields.Contains(product.Category))
    

    又名

    from product in db.Products
    where myFields.Contains(product.Category)
    select product
    

    【讨论】:

      【解决方案2】:

      正如其他人所提到的,是的,它确实使用 .Contains 方法。为了使可能通过 Bing(或任何其他搜索引擎)到达这里的其他随机人受益:Linq-To-Entities 在当前版本中不支持 .Contains 方法。但是,通过简单的扩展方法,您可以这样做:
      http://george.tsiokos.com/posts/2007/11/30/linq-where-x-in/

      【讨论】:

        【解决方案3】:

        理论上你会使用 contains:

        var productList = from product in context.Products
            where myfields.contains(product.category)
            select product
        

        但是您需要对此进行测试-我似乎记得在尝试处理 List 时 Linq2Sql 优化器中存在一个错误,并且数组值被这样使用(它可能仅在您尝试强制转换时发生它们作为 IQueryable)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-25
          • 2023-01-13
          • 2010-09-10
          相关资源
          最近更新 更多