用于与条件相交的Linq方法

时间:2016-06-09 09:38:39

标签: c# .net linq

我有以下POCO:

public class User {
    public ICollection<DepartmentPosition> DepartmentPositions { get; set; }
    public PerformanceRecord PerformanceRecord { get; set; }
}

其中DepartmentPosition定义为:

public class DepartmentPosition {
   public Department Department { get; set; }
   public PositionType PositionType { get; set; }
}

PositionType是枚举,定义为:

 public enum PositionType : byte {
     Employee = 0,
     Manager = 1
 }

我希望能够查询Manager是否能够看到Employee PeformanceRecord

标准是:

如果管理员的DepartmentPosition PositionType ManagerDepartmentPosition的{​​{1}}也Department等于Department在任何员工DepartmentPositions中,经理将能够看到员工的绩效记录。

有一个规范类用于此:

public CanUserSeePerformanceRecord() {
    public bool IsSatisfiedBy(User fooUser, User barUser) {
         // PSUEDO CODE

         // Returns true if:

         // fooUser and barUser both have a DepartmentPosition with the same Department AND for barUser, the PositionType of the DepartmentPosition is Manager
    }
}

我认为您可以使用Linq Intersect或类似功能,但不确定如何包含barUser必须包含标记为DepartmentPosition的{​​{1}}的条件。

2 个答案:

答案 0 :(得分:2)

假设部门有一个ID字段来唯一标识它。你应该能够做到这一点:

return barUser.DepartmentPositions
         .Where(x => x.PositionType == PositionType.Manager)
         .Select(x => x.Department.Id)
         .Intersect(fooUser.DepartmentPositions.Select(x => X.Department.Id))
         .Any()

答案 1 :(得分:0)

只是为了表明另一种方式,您也可以使用连接

return (
        from dBar in barUser.DepartmentPositions
                            .Where(m => m.PositionType == PositionType.Manager)
        join dFoo in fooUser.DepartmentPositions 
                 on dBar.Department.Id equals dFoo.Department.Id
        select 1)
      .Any()

(
 from dBar in barUser.DepartmentPositions                              
 join dFoo in fooUser.DepartmentPositions 
                     on dBar.Department.Id equals dFoo.Department.Id
 where dBar.PositionType == PositionType.Manager
 select 1)
 .Any()