|
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
Leave a Reply
8280 views, 2 so far
today |
Follow Discussion
8 Responses to “LINQ Equivalent Of Where IN”
Trackbacks
- LINQ Equivalent Of Where IN With Int | One .Net Way January 5th, 2009
Leave a Reply
Get Updates By Email
Popular Post
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Free Icons And Images With Visual Studio 2008
- Windows 7 Control Panel In Classic Mode
- Dynamic Sort With LINQ
- Use SqlConnection With LINQ To SQL
- StyleCop Tutorial
- Write To Vista Event Log Using C#
- More Details Emerge On Microsoft Master Certification
Tag Cloud
Code Snippets
- Get Current Windows User In C#
- Get Width And Height Of Image In C#
- Get Windows Registry Size With WMI And C#
- Reverse Array Elements Using C#
- Convert Hexadecimal To Number In C#
- Get Free Disk Space Using T-SQL
- SQL Server 2008 – Get All Indexes In A Database
- Get Name Of Current Executing Assembly In C#
- Get CD Or DVD Drive Information Using WMI And C#
- Get Last Row From Table Using LINQ To SQL


September 24th, 2008 at 11:58 pm
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;
September 25th, 2008 at 7:45 am
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.
October 15th, 2008 at 9:27 pm
ArrayList is not supported
January 5th, 2009 at 12:59 am
This only works with strings ?
January 5th, 2009 at 9:04 am
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/
February 1st, 2009 at 10:10 pm
Thank you, Deepak, very useful.
February 2nd, 2009 at 5:26 am
Lucia,
Thank you for the kind words.