proseidon
proseidon

Reputation: 2305

Finding in a list that contains an attribute of an object

I'm trying to find which items in my list fill a certain criteria.

I have a List<Employee>, and each Employee has a List<Role> attribute. Each Role has an ID as an attribute. I'm trying to find all Employees that have a certain Role ID in the list. Here is my non-working sample:

var query = EmployeeList.Where(employee=> employee.Roles.Contains(role => role.ID == roleID)).ToList();

Upvotes: 0

Views: 82

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499810

You can just change your Contains to Any (as you're just checking whether any of the roles of the employee matches your condition):

var query = EmployeeList.Where(employee => employee.Roles
                                                 .Any(role => role.ID == roleID))
                        .ToList();

Note that this won't be a terribly efficient approach - every employee has to be checked, and every role of every employee. If you need to do this often with the same set of employees but different role IDs, you could build a lookup from role ID to employees:

var lookup = EmployeeList.SelectMany(e => e.Roles,
                                     (e, r) => new { Employee = e, Role = e })
                         .ToLookup(pair => pair.Role.ID,
                                   pair => pair.Employee);

You can then just use:

foreach (var employee in lookup[roleID])
{
    ....
}

Upvotes: 4

Habib
Habib

Reputation: 223187

Use Enumerable.Any

var query = EmployeeList.Where(employee => employee.Roles
                                                   .Any(role => role.Id == roleID))
                                                   .ToList();

Upvotes: 6

Related Questions