Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Where in collection clause

Tags:

c#

linq-to-sql

I've been looking on google but not finding anything that does the trick for me.

as you know SQL has a "where x in (1,2,3)" clause which allows you to check against multiple values. I'm using linq but I can't seem to find a piece of syntax that does the same as the above statement.

I have a collection of category id's (List) against which I would like to check

I found something that uses the .contains method but it doesn't even build.

like image 261
Jan W. Avatar asked Jun 10 '09 06:06

Jan W.


People also ask

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

What is the difference between select and where in LINQ?

Select will always return the same number of elements in the list (regardless of a filter condition you may have). Where can return less elements depending on your filter condition.

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 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.


2 Answers

You have to use the Contains method on your id list:

var query = from t in db.Table
            where idList.Contains(t.Id)
            select t;
like image 105
Christian C. Salvadó Avatar answered Oct 24 '22 01:10

Christian C. Salvadó


The syntax is below:

IEnumerable<int> categoryIds = yourListOfIds;

var categories = _dataContext.Categories.Where(c => categoryIds.Contains(c.CategoryId));

The key thing to note is that you do the contains on your list of ids - not on the object you would apply the in to if you were writing sql.

like image 19
David Hall Avatar answered Oct 24 '22 02:10

David Hall