Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL: WHERE IN statement

Tags:

c#

sql

linq

CREATE TABLE [MyNames]
(
    [ID] INT IDENTITY PRIMARY KEY,
    [Name] NVARCHAR(255) NULL
)

INSERT INTO [MyNames] VALUES ('John')
INSERT INTO [MyNames] VALUES ('Jane')
INSERT INTO [MyNames] VALUES ('Peter')
INSERT INTO [MyNames] VALUES ('Montgomery')
INSERT INTO [MyNames] VALUES ('Sarah')

Based on the above (hypothetical) SQL schema and data, I want to use Linq to SQL to get all results where the name is in values of an array.

string[] names = {"John", "Cassandra", "Sarah"};

var results = (from n in db.Names
               where n.Name **in names**
               select n).ToList();

The results should include John and Sarah. With that information I am then able to add the entries that need to be added, in this case Cassandra.

I don't want to load all the Names because the list can get exceptionally long.

like image 362
Clarice Bouwer Avatar asked Aug 14 '13 15:08

Clarice Bouwer


People also ask

What is the LINQ equivalent to the SQL IN operator?

Perform the equivalent of an SQL IN with IEnumerable. Contains().

How do you query in LINQ?

In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).

Is LINQ better than stored procedure?

Stored procedures are faster as compared to LINQ query since they have a predictable execution plan and can take the full advantage of SQL features. Hence, when a stored procedure is being executed next time, the database used the cached execution plan to execute that stored procedure.

How can I see SQL generated by LINQ?

You can view the SQL code generated for queries and change processing by using the Log property. This approach can be useful for understanding LINQ to SQL functionality and for debugging specific problems.


1 Answers

You can use names.Contains():

string[] names = {"John", "Cassandra", "Sarah"};

var results = (from n in db.Names
               where names.Contains(n.Name)
               select n).ToList();
like image 156
jmoerdyk Avatar answered Oct 02 '22 14:10

jmoerdyk