我正在尝试使用LINQ加入两个表员工和部门,并尝试以下面的图像格式获得结果。有人可以帮助如何实现这一目标。
如何实现每个部门的员工。
这是我的代码
var EmpList = (from d in Department
join e in Employee on d.ID equals e.ID
select new
{
ID = d.ID, Name = d.Name, Location = d.location, Employess =
e.FirstName, e.LastName, e.Gender
});
以上代码未完全编写。我没有得到任何想法如何实现这一点。
var elist = from d in db.Departments
join e in db.Employees on d.ID equals e.ID
group d by e.DepartmentId into g
select new { Details = g };
答案 0 :(得分:1)
假设你有这样的结构:
var depts = new[] {
new Dept { ID = 1, Name = "IT", Location = "New York" },
new Dept { ID = 2, Name = "HR", Location = "London" },
new Dept { ID = 3, Name = "Payroll", Location = "Sydney" }
};
var employees = new[] {
new Employee { ID = 1, FirstName = "Mark", DeptID = 1 },
new Employee { ID = 2, FirstName = "Steve", DeptID = 3 },
new Employee { ID = 3, FirstName = "Ben", DeptID = 1 },
new Employee { ID = 4, FirstName = "Philip", DeptID = 2 },
new Employee { ID = 5, FirstName = "Mary", DeptID = 2 },
new Employee { ID = 6, FirstName = "Valarie", DeptID = 3 },
new Employee { ID = 7, FirstName = "John", DeptID = 1 }
};
您可以使用LINQ Join和GroupBy来获取所需的数据:
var result = depts
.Join(employees.GroupBy(x => x.DeptID), dept => dept.ID, empGroup => empGroup.Key,
(dept, empGroup) => new {
Name = dept.Name,
Location = dept.Location,
Employees = empGroup.ToArray()
});
或者类似于SQL的语法:
var result = from dept in depts
join empGroup in (
from e in employees
group e by e.DeptID into g
select g
) on dept.ID equals empGroup.Key
select new {
Name = dept.Name,
Location = dept.Location,
Employees = empGroup.ToArray()
};
这实际上是做什么的?
DeptID
分组。答案 1 :(得分:0)
public class Meta
{
}
公共偏见类员工
{
public string depart
{
get
{
EmpolyeeEntities db = new EmpolyeeEntities();
var empid = db.Empolyees.Select(e=>e.Department).SingleOrDefault();
var dpname = db.Department1.Where(x => x.Id == empid).Select(f => f.Department).SingleOrDefault();
return dpname.ToString();
}
}