Bhav
Bhav

Reputation: 2195

Filter a list of objects based on a property existing in another list

I've got a class named Container that includes an int property named Id.

I've got a list of objects List<Container> named containers.

I've got a list of numbers List<int> named containerIds.

How can I get a subset of containers where the Id is in containerIds?

Something like the following:

var result = containers.Where(x => x.Id IN containerIds);

Upvotes: 0

Views: 1324

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23238

You might use Contains method for that

var result = containers.Where(x => containerIds.Contains(x.Id));

Another option is to use Any Linq method

var result = containers.Where(x => containerIds.Any(i => i == x.Id));

Upvotes: 3

Related Questions