LINQ Equivalent Of Where IN
Working with LINQ to SQL I came across a need of writing a LINQ query equivalent of T-SQL “Where IN” clause. This is what T-SQL query looks like.
SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address,
City, Region, PostalCode, Country, Phone, Fax
FROM Customers
WHERE (Country IN ('UK', 'USA', 'Australia'))
How do I write Where IN in LINQ?
Below is the query which can be used for a “WHERE IN” scenario. Query 1 uses query syntax and Query 2 uses lambda expression. I am using using a DataContext for Northwind database. See LINQ To SQL Tutorial to see how to generate a DataContext.
LINQ Query 1
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers =
from c in context.Customers
where countries.Contains(c.Country)
select c;
LINQ Query 2
string[] countries = new string[] { "UK", "USA", "Australia" };
var customers =
context.Customers
.Where(c => countries.Contains(c.Country));
Technorati Tags: LINQ
Tagged with: LINQ
8 Responses to LINQ Equivalent Of Where IN
Leave a Reply Cancel reply
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML


couldn’t I write it that way?
var customers = from c in context.Customers
where (c.Country == “UK” || c.Country == “USA” ||
c.Country == “Australia”)
select c;
Yes that will also work.
The solution I posted will also work when the elements of the array are unknown. Imagine this array being generated dynamically.
ArrayList is not supported
This only works with strings ?
[...] I wrote a post showing how to write a LINQ query which gets transformed into a T-SQL query with a "Where In" clause. I had a comment on the post by Steve saying that the approach only works with strings. In this [...]
Hi Steve,
Here is a post I wrote which shows you how to do this with integers. I hope you will find it useful.
http://www.thereforesystems.com/linq-equivalent-of-where-in-with-int/
Thank you, Deepak, very useful.
Lucia,
Thank you for the kind words.