Majkeli
Majkeli

Reputation: 187

How to filter list of objects with child collection by list of strings

I have two lists, a list strings called sectionRoles and a list of User objects called appUsers. The User class has a collection of Role classes. I want to filter the appUsers list where any of their Role.RoleName properties has an entry in the sectionRoles list.

How would I do that? Preferably in method syntax.

Upvotes: 0

Views: 27

Answers (1)

René Vogt
René Vogt

Reputation: 43876

That's simple enough:

var usersWithRoles = appUsers.Where(user => 
              user.Roles.Any(role => sectionRoles.Contains(role.RoleName))).ToList();

This checks for each user in appUsers if Any of it's Roles has a RoleName that is contained in the sectionRoles list.

Upvotes: 1

Related Questions