title: Split datatable to list object C# using LINQ or Entity Framework
body: <p>I have a datatable which contains some rows as a result of joining two tables using the below query:</p>
  
  <pre><code>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
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/62G9W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/62G9W.jpg" alt="enter image description here"></a></p>
  
  <p>On the other hand, I have these classes:</p>
  
  <pre><code>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&lt;Employee&gt; Employees { get; set; }
  }
  </code></pre>
  
  <p>So, how can I convert the given datatable to a list of <code>Departments</code>, and each department has its own list of employees and so on ...</p>
  
  <p>The basic solution which does the same requirement, it could be as follows, but it is not a professional one and it might hit the performance with big amount of data, especially if we are talking about multiple joins, not like the provided simple example:</p>
  
  <pre><code>var depts = new List&lt;Department&gt;();
  var view = dt.DefaultView.ToTable(true, "DeptId", "DeptName");
  foreach (DataRow row in view.Rows)
  {
      var dep = new Department();
      var depEmployees = new List&lt;Employee&gt;();
      dep.Id = int.Parse(row["DeptId"].ToString());
      dep.Name = row["DeptName"].ToString();
      foreach (var emp in dt.AsEnumerable()
          .Where(w =&gt; 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);
  }
  </code></pre>