我有Employee
列表
EmpId EmpName ManagerId Salary
ManagerId
是EmpId
我想从同一个列表中获取EmpName
,ManagerName
(使用ManagerId
获取EmpName
)。
请任何人帮助我..
List<Employee> emp = new List<Employee>();
emp.Add(new Employee() { Empid = 1, EmpName = "Arivu", Managerid=null, salary = 20000 });
emp.Add(new Employee() { Empid = 2, EmpName = "kavi", Managerid=1, salary = 30000 });
emp.Add(new Employee() { Empid = 6, EmpName = "karthi", Managerid = 1, salary = 307000 });
emp.Add(new Employee() { Empid = 3, EmpName = "Anbu", Managerid = 2, salary = 40000 });
emp.Add(new Employee() { Empid = 4, EmpName = "asfdsf", Managerid = 1, salary = 55000 });
emp.Add(new Employee() { Empid = 5, EmpName = "Nithya", Managerid = 3, salary = 12000 });
这是列表,我想从empname
列表中获取managername
和emp
答案 0 :(得分:5)
var result = from emp in empList
join mng in empList on emp.ManagerId equals mng.Id
select new {
emp.EmpName,
ManagerName = mng.EmpName
};
或
var result = empList.Join(empList , emp => emp.ManagerId, mng => mng.EmpId, (emp, mng) => new
{
emp.EmpName,
ManagerName = mng.EmpName
});
答案 1 :(得分:0)
我经常尝试避免SelectMany
查询,因为它们并不总是最具可读性。因此,根据具体情况,我可能会这样做:
var map = emp.ToDictionary(e => (int?)e.Empid);
Func<int?, string> getNameFromId = i =>
i == null ? "n/a" : map[i].EmpName;
var query =
from e in emp
select new
{
e.EmpName,
ManagerName = getNameFromId(e.Managerid)
};
我发现这种事情更加明确,特别是因为当某人没有经理时,它明确地处理了这种情况。