使用LINQ或实体框架将数据表拆分为列出对象C#

时间:2018-06-22 10:28:48

标签: c# entity-framework linq datatable

我有一个数据表,其中包含一些行,这是通过使用以下查询将两个表联接在一起的结果:

SELECT 
    e.Id AS EmpId,
    e.Name AS EmpName,
    d.Id AS DeptId,
    d.Name AS DeptName
FROM  
    Departments D
JOIN 
    Employees E ON D.Id = E.DeptId

enter image description here

另一方面,我有这些课程:

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public int DeptId { get; set; }
}

class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Employee> Employees { get; set; }
}

因此,如何将给定的数据表转换为Departments的列表,并且每个部门都有自己的员工列表,依此类推...

具有相同要求的基本解决方案可能如下,但它不是专业的解决方案,它可能会影响大量数据的性能,特别是如果我们在谈论多个联接而不是所提供的联接时简单的例子:

var depts = new List<Department>();
var view = dt.DefaultView.ToTable(true, "DeptId", "DeptName");
foreach (DataRow row in view.Rows)
{
    var dep = new Department();
    var depEmployees = new List<Employee>();
    dep.Id = int.Parse(row["DeptId"].ToString());
    dep.Name = row["DeptName"].ToString();
    foreach (var emp in dt.AsEnumerable()
        .Where(w => int.Parse(w["DeptId"].ToString()) == dep.Id).ToList())
    {
        depEmployees.Add(new Employee
        {
            Id = int.Parse(emp["EmpId"].ToString()),
            Name = emp["EmpName"].ToString(),
            City = emp["City"].ToString(),
            DeptId = dep.Id
        });
        dep.Employees = depEmployees;
    }

    depts.Add(dep);
}

3 个答案:

答案 0 :(得分:2)

该解决方案如何:

var view = dt.DefaultView.ToTable(true, "DeptId", "DeptName");
var departments = view.Rows.OfType<DataRow>()
    .ToLookup(row => row["DeptId"])
    .Select(group => new Depatment
        {
            Id = group.Key, // convert somehow
            Name = group.First()["DeptName"], // convert somehow
            Employees = group.Selec(row => new Employee
            {
                Id = row["EmpId"], // convert somehow
                Name = row["EmpName"] // convert somehow
            }).ToList();
        }).ToList();

答案 1 :(得分:1)

IList<Department> departments =
        table.AsEnumerable()
        .GroupBy(d => new
        {
            Id = d.Field<Int32>("DeptId"),
            Name = d.Field<String>("DeptName")
        })
        .Select(grp =>
            new Department
            {
                Id = grp.Key.Id,
                Name = grp.Key.Name
            }).ToList();

答案 2 :(得分:0)

尝试以下操作:

           List<DataTable> deptTables = dt
                .AsEnumerable()
                .GroupBy(x => x.Field<int>("DeptId"))
                .Select(x => x.CopyToDataTable())
                .ToList();

或创建字典

            Dictionary<int, DataTable> deptDict = dt.AsEnumerable()
                .GroupBy(x => x.Field<int>("DeptId"))
                .ToDictionary(x => x.Key, y => y.CopyToDataTable());