How to Use SQL “Where In” with LINQ to SQL

While LINQ to SQL can sometimes look very much like standard SQL, there are many (sometimes subtle) differences. One of those differences is using a SQL "Where In" clause with LINQ to SQL.

As an example, let's say we want to return a list of customers who live in UK, USA, or Australia. I'm using the Northwind database for this example:

SQL Code Example

SELECT     CustomerID, CompanyName, ContactName, ContactTitle, Address,
           City, Region, PostalCode, Country, Phone, Fax
FROM       Customers
WHERE      (Country IN ('UK', 'USA', 'Australia'))


To translate this into LINQ to SQL, we can use the Contains() extension.

 

LINQ to SQL Example Using Contains – Query Syntax

string[] countries = new string[] { "UK", "USA", "Australia" };

var customers =
    from c in context.Customers
    where countries.Contains(c.Country)
    select c;


LINQ to SQL Example Using Contains – Lambda Expression

string[] countries = new string[] { "UK", "USA", "Australia" };

var customers = context.Customers.Where(c => countries.Contains(c.Country));

 

GD Star Rating
loading...
GD Star Rating
loading...
How to Use SQL "Where In" with LINQ to SQL, 2.0 out of 5 based on 3 ratings
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply