Func<Employee, int> getXId = (x => x.EmployeeId);
Func<Employee, int?> getXParentId = (x => x.ManagerId);
Func<Employee, string> getXDisplayName = (x => x.Name);
LoadListItems(employees, getXId, getXParentId, getXDisplayName);
private void LoadListItems<T>(IEnumerable<T> items, Func<T, int> getId, Func<T, int?> getParentId, Func<T, string> getDisplayName)
{
dicNodeList.Clear();
var result = new List<NavigationItem>();
foreach (var item in items)
{
var id = getId(item);
var displayName = getDisplayName(item);
var node = new NavigationItem { ID = id, Name = displayName, NodeInfo = item };
node.Items = new List<NavigationItem>();
dicNodeList.Add(getId(item), node);
}
foreach (var id in dicNodeList.Keys)
{
var currentNode = GetXNode(id);
var nodeInfo = (T)currentNode.NodeInfo;
var parentNodeID = getParentId(nodeInfo);
if (parentNodeID.HasValue && dicNodeList.ContainsKey(parentNodeID.Value))
{
var parent= GetXNode(parentNodeID.Value);
parent.Items.Add(currentNode);
}
else
{
result.Add(currentNode);
}
}
var z = result;
}
public NavigationItem GetXNode(int id)
{
return dicNodeList[id];
}
Dictionary<int, NavigationItem> dicNodeList = new Dictionary<int, NavigationItem>();
public class NavigationItem
{
public int ID { get; set; }
public string Name { get; set; }
public int? ParentID { get; set; }
public List<NavigationItem> Items { get; set; }
public object NodeInfo { get; set; }
}