tags:

views:

37

answers:

1

I need some LINQ advice (or even general advice) on how to implement the following:

Basically, I have 3 entities: Projects -- EmployeeProjects -- Employees (1 to Many and Many to 1 relationship, respectively), i.e. an employee could be assigned to many Projects and a Project could have many Employees and all our housed in EmployeeProjects.

I would like to select a couple of Employees and see if they exist on a certain Project and if they do not exist on that Project, I would like to add them.

So far I'm thinking something like this (any and all advice appreciated!):

var existingEmployees = new List<string>();

foreach(var employeeProject in _project.EmployeeProjects)
{
    if (employeeProject.Employee != null) 
        existingEmployees .Add(employeeProject.Employee.EmployeeId);
}

foreach(var employee in GetSelectedEmployees())
{
    if (!existingEmployees.Contains(employee.EmployeeId))
    {
        _project.AddEmployee(employee);
    }
}
+3  A: 
foreach( var employee in GetSelectedEmployees()
                         .Except(_project.EmployeeProjects.Employees))
     _project.AddEmployee(employee); 

Now, If Project had an AddEmployees(IEnumerable<Employee>) method:

_project.AddEmployees(GetSelectedEmployees()
                         .Except(_project.EmployeeProjects.Employees));
James Curran
Thanks! Exactly what I was looking for.