Tuesday, September 13, 2011

IN clause With Linq To Sql

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 Conains ().:

String [] s = new String [5];
s [0] = "34";
s [1] = "12";
s [2] = "55";
s [3] = "4";
s [4] = "61";

var
RESULT1 =  from d in context.TableName
                        where s.Contains (d.fieldname)
                        select d;
Eg:
int[] productList = new int[] { 1, 2, 3, 4 };

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

Start with the Order (pretend my order is ID=44):
AdventureWorks.DB db=new DB();
 
var itemQuery = from orders in db.SalesOrder
              where orders.SalesOrderID == 44
              select orders.ProductID;
Next we need to get the products, but only those that are in the cart.
We do this by using our first query, inside the second:

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

No comments :

Post a Comment