1

I have 2 data objects. Employee and Manager

class Employee{
int EmpId;
int EmpName }

Class Manager{
int ManagerID; //is the empId of an employee who is Manager
}

I want a list of EmpName who is not a Manager using LINQ in a single statement.

I tried this:

var employeeIdsWhoAreNotManagers = EmployeeList.Select(x=>x.EmpId).Except(Managerlist.Select(x=>x.ManagerId));

but this returns me only EmpId. Then again i have to write one more linq to get the EmpName .

Update1:

 empNamesList = EmployeeList.Where(x=>x.employeeIdsWhoAreNotManagers.Contains(x.empId)).Select(x=>x.empName);

How do I Combine into a single LINQ query which results me the EmpName list directly?

1 Answer 1

6

If it is Linq to object, you can use an extension method ExceptBy

public static IEnumerable<T1> ExceptBy<T1, T2, R>(
    this IEnumerable<T1> source, 
    IEnumerable<T2> other, 
    Func<T1,R> keySelector1, 
    Func<T2,R> keySelector2)
{
    HashSet<R> set = new HashSet<R>(other.Select(x => keySelector2(x)));

    return source.Where(item => set.Add(keySelector1(item)));
}

.

 EmployeeList.ExceptBy(Managerlist, x=>x.EmpId , y=>y.ManagerId));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.