What is the LINQ counterpart of the "IN" keyword in SQL?

entity-framework linq sql-server

Question

How would I put the following SQL query in Linq?

select * from Product where ProductTypePartyID IN
(
    select Id from ProductTypeParty where PartyId = 34
)
1
7
11/24/2011 10:03:20 AM

Accepted Answer

Despite syntactic differences, it may be written in much the same manner.

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

However, I like using the existential quantifier:

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

I anticipate that this form will end in anEXISTS (SELECT * ...) in the SQL produced.

In case there is a significant performance difference, you should profile both.

4
11/24/2011 10:21:29 AM

Popular Answer

In LINQ, there isn't a direct equivalent. To implement them instead, use includes () or any other technique. Here is an illustration usingContains :

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;

For further information, go here: clause in Linq

int[] productList = new int[] { 1, 2, 3, 4 };


var myProducts = from p in db.Products
                 where productList.Contains(p.ProductID)
                select p;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow