c# - 使用 LINQ 查找两个数据对象之间的差异

标签 c# linq

我有 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/

相关文章:

c# - Group By 在两个字段之间来回链接

c# - 从一个 IList<> 中移除另一个 IList<> 中的项目

c# - 使用 linq 对 XMLDocument 进行排序

c# - 根据子元素值选择父 XML 元素 LINQ C#

c# - .Net 2.0 中的 TextBox AutoCompleteMode 属性

c# - Hangfire 禁用并发执行 : What happens when the timeout expires?

c# - 在 Windows 中将窗口保持在另一个窗口的前面(而不是在顶部)

c# - 从 C# 在批处理文件中运行批处理文件

c# - 计算复杂的 lambda 表达式

数组中周围数字的 Linq 表达式