我有 2 个数据对象。员工和经理
class Employee{
int EmpId;
int EmpName }
Class Manager{
int ManagerID; //is the empId of an employee who is Manager
}
我想要在单个语句中使用 LINQ 的不是经理的 EmpName 列表。
我试过这个:
var employeeIdsWhoAreNotManagers = EmployeeList.Select(x=>x.EmpId).Except(Managerlist.Select(x=>x.ManagerId));
但这只返回 EmpId。然后我必须再写一个 linq 来获取 EmpName 。
更新1:
empNamesList = EmployeeList.Where(x=>x.employeeIdsWhoAreNotManagers.Contains(x.empId)).Select(x=>x.empName);
如何组合成一个直接生成 EmpName 列表的 LINQ 查询?
最佳答案
如果是Linq to object,可以使用扩展方法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));
关于c# - 使用 LINQ 查找两个数据对象之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010024/