I am trying to populate a tree view based on a list of staff from various deparments (lstStaff).
public class Staff
{
public int StaffID { get; set; }
public string StaffName { get; set; }
public int DeptID { get; set; }
public string DepartmentName { get; set; }
}
The result should be like this:
Department A
- John
- Dave
Department B
- Andy
- Leon
I have written the following code. However, I think the code should be refactored further.
RadTreeNode deptNode;
RadTreeNode staffNode;
var departments = (from d in lstStaff
where !string.IsNullOrEmpty(d.DepartmentName)
select new { d.DeptId, d.DepartmentName })
.Distinct();
foreach (var d in departments)
{
//add department node
deptNode = new RadTreeNode()
{
Value = d.DeptId,
Text = d.DepartmentName
};
tvwDepartmentCases.Nodes.Add(deptNode);
//add staff nodes to department node
var staffs = lstStaff
.ToList()
.Where(x => x.DeptId == d.DeptId);
foreach (var s in staffs)
{
staffNode = new RadTreeNode()
{
Value = s.StaffID,
Text = s.StaffName
};
deptNode.Nodes.Add(staffNode);
}
}
Any comments are welcomed. Thanks!
Use the
GroupByoperator, it’s easy and looks so much nicer.It’s also lower complexity because you don’t need to iterate through the entire collection of
lstStafffor each department.