Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Linq and the IN clause

Tags:

linq

Here is my code

if (catid != 0)
            posts = posts.Where(x => x.catid IN '1,8,2,109,23');

The in in this code shows as a syntax error. Is there a way to fix this

like image 721
Luke101 Avatar asked Jan 06 '10 20:01

Luke101


People also ask

How use contains in LINQ?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

Can we use multiple where clause in LINQ?

Filter collections using Where clause in C#. A single query expression may have multiple where clauses.

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 to SQL obsolete?

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

You must use another list to compare too.

List<int> cadIdFoundList = new List<int>();

cadIdFoundList.Add(1);
cadIdFoundList.Add(8);
// etc. . . 

posts.Where(x => cadIdFoundList.Contains(x.catId));
like image 68
David Basarab Avatar answered Nov 03 '22 15:11

David Basarab


int[] ids = new int[] { 1, 8, 2, 109, 23 };
var query = posts.Where(x => ids.Contains(x.catid));

Rob Conery has discussed this topic before.

like image 20
jason Avatar answered Nov 03 '22 15:11

jason