Graham
Graham

Reputation: 1517

Linq Method for Intersecting with a Condition

I have the following POCO:

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

where DepartmentPosition is defined as:

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

and PositionType is a enum defined as:

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

I want to be able to query whether a Manager is able to see an Employee PeformanceRecord.

The criteria for this is:

If a Manager has a DepartmentPosition with a PositionType of Manager, and that particular DepartmentPosition also has a Department equal to the Department of any of the Employee's DepartmentPositions, then the Manager will be able to see the Performance Record for the Employee.

There is a specification class being used for this:

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
    }
}

I think you could do it using a Linq Intersect or similar, but not sure how to include the condition that the barUser has to hold a DepartmentPosition that is marked as Manager.

Upvotes: 3

Views: 1300

Answers (2)

Magnus
Magnus

Reputation: 47036

Assuming Department has an ID field to uniquely identify it. You should be able to do this:

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

Upvotes: 2

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Just to show another way, you may also use a join

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()

or

(
 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()

Upvotes: 0

Related Questions