LINQ statement that equal to State IN ('NY','TX'...) SQL Statement

  • Thread starter Thread starter Shimon Sim
  • Start date Start date
S

Shimon Sim

Is it possible to write LINQ statement (LINQ to SQL) that would result in
query with IN key word.
Like
SELECT FirstNAme, LastName FROM People WHERE State IN ('NY', 'NJ', 'TX') ?

Thanks,
Shimon.
 
Shimon,

Yes, it is, but you have to turn it around in a way, and use the
Contains extension method on the set that you want to find the item in, like
so:

// The states.
string[] states = {"NY", "NJ", "TX"};

// The query.
var query = from p in people where states.Contains(p.State) select new {
p.FirstName, p.LastName };
 
Just did experiment and it worked!!
PeopleDataContext dc = new PeopleDataContext();
var results = from p in dc.People select p;
results = from p in results where states.Contains(p.State); // states is a
collection.

Debugging showed where State IN (@P1,@P2) . perfect!!
 
Thanks, I got it.

Nicholas Paldino said:
Shimon,

Yes, it is, but you have to turn it around in a way, and use the
Contains extension method on the set that you want to find the item in,
like so:

// The states.
string[] states = {"NY", "NJ", "TX"};

// The query.
var query = from p in people where states.Contains(p.State) select new {
p.FirstName, p.LastName };


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Shimon Sim said:
Is it possible to write LINQ statement (LINQ to SQL) that would result in
query with IN key word.
Like
SELECT FirstNAme, LastName FROM People WHERE State IN ('NY', 'NJ', 'TX')
?

Thanks,
Shimon.
 
Back
Top