Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate a WHERE...IN clause using LINQ2SQL?

Going backwards from SQL to LINQ2SQL is sometimes quite simple. The following statement

SELECT user FROM users WHERE lastname='jones'

translates fairly easily into

from u in users where u.lastname='jones' select u

But how do you get the following SQL generated?

SELECT user FROM users WHERE lastname IN ('jones', 'anderson')
like image 533
Jedidja Avatar asked Feb 04 '10 14:02

Jedidja


People also ask

How do you implement a clause in LINQ?

Using the List object Contains method in the Where clause will create the IN T-SQL clause. The code snippet uses the Microsoft Northwind sample database using the Customers table as an example. If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

What is where in C#?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.

How use not in LINQ query in C#?

Except operator are designed to allow you to query data which supports the IEnumerable<T< interface. Since all LINQ query expressions, and most LINQ queries, return IEnumerable<T<, these operators are designed to allow you to perform set operations on the results of a LINQ query.

How do I select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.


1 Answers

I had to do a bit of searching to find this, and thought it might be useful to others.

List<string> names = new List<string>() { "jones", "anderson" };

from u in users where names.Contains(u.lastname) select u
like image 99
Jedidja Avatar answered Oct 12 '22 10:10

Jedidja