【问题标题】:What is LINQ equivalent of SQL’s "IN" keyword什么是 LINQ 等效于 SQL 的“IN”关键字
【发布时间】:2011-11-24 10:03:20
【问题描述】:

如何在 linq 中编写下面的 sql 查询

select * from Product where ProductTypePartyID IN
(
    select Id from ProductTypeParty where PartyId = 34
)

【问题讨论】:

    标签: sql-server linq entity-framework


    【解决方案1】:

    在 LINQ 中没有直接的等价物。相反,您可以使用 contains () 或任何 实现它们的其他技巧。这是一个使用Contains的示例:

    String [] s = new String [5];
    s [0] = "34";
    s [1] = "12";
    s [2] = "55";
    s [3] = "4";
    s [4] = "61";
    
    var  result = from d in  context.TableName
                  where s.Contains (d.fieldname)
                  select d;
    

    查看此链接了解详情:in clause Linq

    int[] productList = new int[] { 1, 2, 3, 4 };
    
    
    var myProducts = from p in db.Products
                     where productList.Contains(p.ProductID)
                    select p;
    

    【讨论】:

    • 这是如何获得投票的?它假设 OP 想要过滤多个数字,但事实并非如此,并且它使用了问题明显需要处理数字的字符串。
    【解决方案2】:

    抛开句法变化不谈,你可以用几乎相同的方式编写它。

    from p in ctx.Product
    where (from ptp in ctx.ProductTypeParty
           where ptp.PartyId == 34
           select ptp.Id).Contains(p.ProductTypePartyID)
    select p
    

    不过,我更喜欢使用存在量词:

    from p in ctx.Product
    where (from ptp in ctx.ProductTypeParty
           where ptp.PartyId == 34
           && ptp.Id == p.ProductTypePartyID).Any()
    select p
    

    我希望此表单将解析为生成的 SQL 中的 EXISTS (SELECT * ...)

    您需要对两者进行分析,以防性能差异很大。

    【讨论】:

      【解决方案3】:

      类似的东西

      var partyProducts = from p in dbo.Product 
                          join pt in dbo.ProductTypeParty on p.ProductTypePartyID equal pt.PartyId 
                          where pt.PartyId = 34 
                          select p
      

      【讨论】:

        【解决方案4】:

        您在 Where 子句中使用 Contains。

        类似的东西(未经测试):

        var results = Product.Where(product => ProductTypeParty
                                                    .Where(ptp => ptp.PartyId == 34)
                                                    .Select(ptp => ptp.Id)
                                                    .Contains(product.Id)
                                   );
        

        【讨论】:

          猜你喜欢
          • 2011-01-21
          • 1970-01-01
          • 2014-09-08
          • 1970-01-01
          • 1970-01-01
          • 2019-11-09
          • 2010-12-26
          • 1970-01-01
          相关资源
          最近更新 更多