使用LINQ查找两个数据对象之间的差异 [英] Find difference between two Data Objects using LINQ

查看:50
本文介绍了使用LINQ查找两个数据对象之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数据对象.员工和经理

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
}

我想要一个不是在单个语句中使用LINQ的Manager的EmpName列表.

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

我尝试过:

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

但这仅返回EmpId.然后我又不得不再写一个linq来获得EmpName.

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

更新1:

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

如何合并为一个直接生成EmpName列表的LINQ查询?

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

推荐答案

如果是对象的Linq,则可以使用扩展方法ExceptBy

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

这篇关于使用LINQ查找两个数据对象之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆