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.
Perform the equivalent of an SQL IN with IEnumerable. Contains().
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 ).
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With