zoukankan      html  css  js  c++  java
  • Linq 如何实现 in 与 not in

    接触 LINQ 也有很长的一段时间了,有些在 SQL 语句中用的很顺手的东西在 Linq 中却不知道如何实现了,最近遇到了一个问题,在 LINQ 的 Where 条件式中要如何使用 IN 与 NOT IN 呢? 这时候真的开始怀念 T-SQL 其实还是最好用的。为了让自己日后开发时更为方便,于是花了一点时间,参考一些网络资料及 MSDN 后,得到以下的测试結果:

    T-SQL的IN:

    Select ProductID, ProductName, CategoryID
    From dbo.Products
    Where CategoryID in (1, 2)

    T-SQL的NOT IN:

    Select ProductID, ProductName, CategoryID
    From dbo.Products
    Where CategoryID not in (1, 2)

    Or

    Select ProductID, ProductName, CategoryID
    From dbo.Products
    Where not CategoryID in (1, 2)

    LINQ的IN:

    var queryResult = from p in db.Products
    where (new int?[] {1,2}).Contains(p.CategoryID)
    select p;

    LINQ的IN解析成SQL:

    SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
    FROM [dbo].[Products]AS [t0]
    WHERE [t0].[CategoryID] IN (@p0, @p1)

    LINQ的NOT IN:

    var queryResult = from p in db.Products
    where ! (new int?[] {1,2}).Contains(p.CategoryID)
    select p;

    LINQ的NOT IN解析成SQL:

    SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
    FROM [dbo].[Products]AS [t0]
    WHERE NOT [t0].[CategoryID] IN (@p0, @p1)


    转载自:http://blog.csdn.net/zhangyumei/article/details/5620363

    标签: , ,
  • 相关阅读:
    cocos2dx3.0戳青蛙游戏(打地鼠)
    深入理解Tomcat系列之五:Context容器和Wrapper容器
    linux下拷贝隐藏文件
    8.8.1 运行计划
    UVALive
    堆排序实现
    C语言中的signal函数
    uboot和内核分区的改动
    Android缩放动画
    .Net 自定义应用程序配置
  • 原文地址:https://www.cnblogs.com/xakml/p/7233517.html
Copyright © 2011-2022 走看看