public static List<DepartmentFlat> doFlat(IEnumerable<CompanyDepartment> departments) { List<DepartmentFlat> result = new List<DepartmentFlat>(); foreach (var grp in departments.GroupBy(d => d.CompanyId)) { var tree = dbToTree(grp.ToArray()); var path = new Department[DepartmentFlat.maxDeep]; ForEach(tree, 0, path, (pth, lev) => { DepartmentFlat res = new DepartmentFlat(); for (int i = 0; i <= lev; i++) res.setLevel(i, pth[i].Id, pth[i].Title); var fakeId = pth[lev].Id; for (int i = lev + 1; i < DepartmentFlat.maxDeep; i++) res.setLevel(i, fakeId, null); result.Add(res); }); } return result; }