Fike Rehman
Fike Rehman

Reputation: 815

In place intersection of two collections of different types

I have a collection of Employee objects

IEnumerable<Employee> employees;

where employee looks like this:

    class Employee
    {
        int Id {get; set;}
        int Name {get; set;}
    }

I have a second collection:

IEnumerable<int> fired;

I want to do an intersection of employees and fired in place based on the Id property of the Employee. Something like:

employees.Intersect(fired)

This of course won't work because employee and fired are different types. I know I can do something like this:

List<int> empIds = null;
employees.Foreach(x => empIds.Add(x.Id);

and then do a intersection of empIds and fired and then merge it back. But there must be a way to do this in place without declaring a new List. My goal is to have a method where you pass in the employees collection by reference and it would 'filter out' the fired employees:

void YourRFired(ref IEnumerable<employee> employees)
{
    IEnumerable<int> fired = .....

   // intersect employee and fired here to get a list of employees that are      
    not fired.
}  

Thanks

Upvotes: 2

Views: 201

Answers (2)

Jason Meckley
Jason Meckley

Reputation: 7591

something like

IEnumerable<Employee> employees;
IEnumerable<int> firedEmployeeIds;

//return all employees who are not fired
return employees
    .GroupJoin(firedEmployeeIds, e => e.Id, f => f, (employee, ids) => new 
    { 
        employee, 
        fired = ids.Any() == false 
    })
    .Where(x => x.fired == false)
    .Select(x => x.employee);

Upvotes: 1

drew
drew

Reputation: 1312

How about a where?

var notFiredEmployees = employees.Where(e=>!fired.Contains(e.Id));

Upvotes: 2

Related Questions