I was wondering if someone could help me in generating a linq query for the following scenario.
Here are the classes with the relevant properties:
public class Employee
{
IList<Employee> DirectReports { get; set;}
IList<BonusPlan> BonusPlans { get; set;}
BonusPlanTemplate BonusPlanTemplate { get; set;}
}
public class BonusPlan
{
FiscalPeriod FiscalPeriod { get; set; }
Employee Employee { get; set;}
}
I’m trying to create a method:
IEnumerable<Employee> GetDirectReportsWithoutBonusPlansCreatedForFiscalPeriod(FiscalPeriod fiscalPeriod)
So basically I have this to get the directreports with bonus plans for a particular fiscal period:
var query = from dr in DirectReports
from bp in dr.BonusPlans
where bp.Employee.BonusPlanTemplate != BonusPlanTemplate.Empty &&
bp.FiscalPeriod==fiscalPeriod
select dr;
IList<Employee> directReportsWithBonusPlansCreated = query.ToList();
Then I get all of the DirectReports that should have bonus plans setup (indicated by having a BonusPlanTemplate assigned) that aren’t in the list from the previous query.
var query2 = from dr in DirectReports
where dr.BonusPlanTemplate != BonusPlanTemplate.Empty &&
!directReportsWithBonusPlansCreated.Contains(dr)
select dr;
This produces the correct results but it seems like there must be another way. I’m not sure if I need to do this in two steps. Can someone please help me to combine these two linq queries and possibly make it more efficient. I have relatively little experience with Linq.
Do you need the first query for any other reason? If not, it’s pretty easy:
You could make your life easier use an extra method in
Employee:Then your original first query becomes:
and the second query becomes: