Friday, January 9, 2009

LINQ to SQL - IN Operator

 

The IN operator allows you to specify multiple values in a WHERE clause.

SQL IN Syntax
SELECT  customerId, customerName FROM Customer
WHERE Country IN ('UK','USA').


In LINQ to SQL how can we achieve this.

            string [] CountryList ={"UK","USA"};


            using (NWDataContext dbconn = new NWDataContext())  // Northwind DB 
            {


                var custRecords = from cust in dbconn.Customers   // Customer Table

                                  where CountryList.Contains(cust.Country)

                                  select cust;


                foreach (var item in custRecords)

                {

                    Console.WriteLine(item.CustomerID + " "+ item.Country );    
              }


The above LINQ TO SQL code converted to SQL Statement as shown below.


image


Thanks


SreenivasaRagavan

1 comment:

Sreekanth said...

Thank you. I was wondering how to acheieve this and went through some msdn documentation links, but this one clearly explained what to do.