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)

    实例:

     

     var topicListid = (from t in db.TopicInCategory
                                     where t.TopicCategoryInfoID == id
                                     select t.TopicInfoID).ToList();
    
    
     var topicinfos = from t in db.TopicInfo
                      where !(topicListid).Contains(t.TopicInfoID)
                      select t;

     

     

  • 相关阅读:
    非冒泡事件的冒泡支持
    js--题目二
    js-- 一些题目
    jQuery 请指出'$'和'$.fn'的区别?或者说出'$.fn'的用途。
    jQuery 请指出'.bind()','.live()'和'.delegate()'的区别
    什么时候不能完全按照设计稿来
    edm注意细节
    响应式设计
    css -- 题目汇总
    什么是Handler(四)
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/4464972.html
Copyright © 2011-2022 走看看