[英]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. 我有一个
List<Employee>
,每个Employee
都有一个List<Role>
属性。 Each Role
has an ID
as an attribute. 每个
Role
都有一个ID
作为属性。 I'm trying to find all Employee
s that have a certain Role ID
in the list. 我正在尝试查找列表中具有特定
Role ID
所有Employee
。 Here is my non-working sample: 这是我的无效示例:
var query = EmployeeList.Where(employee=> employee.Roles.Contains(role => role.ID == roleID)).ToList();
Use Enumerable.Any 使用Enumerable.Any
var query = EmployeeList.Where(employee => employee.Roles
.Any(role => role.Id == roleID))
.ToList();
You can just change your Contains
to Any
(as you're just checking whether any of the roles of the employee matches your condition): 您可以将“
Contains
更改为“ Any
(因为您只是在检查员工的任何角色是否符合您的条件):
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:
如果需要经常使用相同的一组雇员但使用不同的角色ID来执行此操作,则可以从角色ID到雇员进行查找:
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])
{
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.