Reputation: 2377
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?
Upvotes: 1
Views: 1131
Reputation: 35363
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));
Upvotes: 6