Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the linq equivalent to the SQL IN operator

Tags:

sql

contains

linq

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:

WHERE ID IN (2,3,4,5) 

How can I do it?

like image 454
Luca Romagnoli Avatar asked Feb 25 '10 13:02

Luca Romagnoli


People also ask

What is LINQ to SQL?

LINQ to SQL is a component of . NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. Relational data appears as a collection of two-dimensional tables (relations or flat files), where common columns relate tables to each other.

Is LINQ same as SQL?

The main difference between LINQ and SQL is that LINQ is a Microsoft . NET framework component that adds native data querying capabilities to . NET languages, while SQL is a standard language to store and manage data in RDBMS.

How can I use SQL like in LINQ?

In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL.

Is LINQ to SQL still used?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.


2 Answers

.Contains

var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x 

Of course, with your simple problem, you could have something like:

var resultset = from x in collection where x >= 2 && x <= 5 select x 
like image 135
David Morton Avatar answered Oct 11 '22 13:10

David Morton


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

var idlist = new int[] { 2, 3, 4, 5 };  var result = from x in source           where idlist.Contains(x.Id)           select x; 
like image 38
Lachlan Roche Avatar answered Oct 11 '22 14:10

Lachlan Roche