简体   繁体   中英

Left Outer Join LINQ

I have a LINQ query that will sort through lists of company employees and attendees in company meetings. I want to extract employees who are not attendees in meetings. Thus, a left outer join seems to be the best LINQ strategy. When I debugged and stepped through the code, employeesNotInMeetings returned all employees, failing to remove the employees who were meeting attendees. Why does this left outer join fail to remove the proper list entries?

        //Query for all attendees who are employees
        List<Attendee> employeesWhoAreAttendees = db.Attendees.Select(ea => ea).ToList();
        //Query for all employees in database
        List<Employee> employees = db.Employees.Select(ee => ee).ToList();

        var employeesNotInMeetings = from emp in employees
                                     join att in employeesWhoAreAttendees
                                     on emp.EmployeeID equals att.EmployeeID into gj
                                     from gji in gj.DefaultIfEmpty()
                                     //If EmployeeID < 0, the attendee is not an employee
                                     where emp.EmployeeID > 0 
                                     select emp;

尝试这样的事情:

employees.Where(x => employeesWhoAreAttendees.All(y => x.EmployeedID != y.EmployeeID))

I'm thinking you probably want something like:

db.Employees.Where(e => !e.Attendees.Any());

Note that this is assuming you have a foreign key set up between the employee and attendee tables, and that the ICollection navigation property on Employee is named Attendees

Also please note, you generally shouldn't call ToList() directly on an unfiltered DBSet. It will pull back the entire table into memory, then do the filtering. You are going to get better performance if you let SQL do the filtering for you.

That is what a left join is supposed to do: it returns all entries on the left side ( employees ) even if there is no result on the right side ( employeesWhoAreAttendees ). If you want to get employees not in meetings - then you should use left excluding join and find those entries in the table employees where there is no entry (null) in the table employeesWhoAreAttendees

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM