简体   繁体   中英

Find difference between two Data Objects using LINQ

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?

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));

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