Roman
Roman

Reputation: 4513

Using IN on a list of objects

I'm trying to use LINQ on a list inside an object. I'll try to explain:

I've got an object called "Comment". In the comment object I have a list of "User" objects, where each user object has an "ID" field.

such as

Public class Comment {
List<User> users;
...
}

Then, I get a list of user ids (let's call it UsersList, such as UsersList is a List< int > object) and would like to get all comments where all users in the UsersList are in the "users" list of that comment.

So if UsersList = {1,2} I would like to get all comments where the user with an id of 1 and the user with an id of 2 will be present in the "users" list.

How can this be achieved?

Thanks!

Upvotes: 0

Views: 94

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

Query it the other way round, i.e. instead of asking "userId in listOfIds", ask "listOfIds.Contains(userId)".

var query = comments
    .Where(c => UsersList.All(id => c.users.Any(u => u.ID == id)));

Upvotes: 1

JotaBe
JotaBe

Reputation: 39014

As simple as this:

comments.Where(c => UsersList.All(uId => c.users.Contains(u => u.Id == uId)));

Upvotes: 0

cuongle
cuongle

Reputation: 75306

comments.Where(c => usersList.All(id => c.users.Any(user => user.Id == id)));

Upvotes: 3

Related Questions