What is LINQ equivalent of SQL’s “IN” keyword

后端 未结 4 1636
暗喜
暗喜 2021-01-05 00:22

How can I write below sql query in linq

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


        
相关标签:
4条回答
  • 2021-01-05 00:59

    There is no direct equivalent in LINQ. Instead you can use contains () or any other trick to implement them. Here's an example that uses 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;
    

    check this link for details: 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;
    
    0 讨论(0)
  • 2021-01-05 01:11

    Syntactic variations aside, you can write it in practically the same way.

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

    I prefer using the existential quantifier, though:

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

    I expect that this form will resolve to an EXISTS (SELECT * ...) in the generated SQL.

    You'll want to profile both, in case there's a big difference in performance.

    0 讨论(0)
  • 2021-01-05 01:14

    You use the Contains in a Where clause.

    Something along these lines (untested):

    var results = Product.Where(product => ProductTypeParty
                                                .Where(ptp => ptp.PartyId == 34)
                                                .Select(ptp => ptp.Id)
                                                .Contains(product.Id)
                               );
    
    0 讨论(0)
  • 2021-01-05 01:22

    Something similar to this

    var partyProducts = from p in dbo.Product 
                        join pt in dbo.ProductTypeParty on p.ProductTypePartyID equal pt.PartyId 
                        where pt.PartyId = 34 
                        select p
    
    0 讨论(0)
提交回复
热议问题