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)

  • 相关阅读:
    host文件的用处
    探究 Flex 组件的生命周期
    QQ在开发中的应用
    转:linux进程间通信的几种机制的比较及适用场合
    转:Linux 2.4.x内核软中断机制
    转:PLL 锁相环
    转:LPC2214的PLL与定时器设置
    转: V4L2驱动程序架构
    转:linux select 多路复用机制
    [转] Linux 句柄是什么 ?
  • 原文地址:https://www.cnblogs.com/ajunForNet/p/4378684.html
Copyright © 2011-2022 走看看