I am writing a method to create a folder tree. I am getting the data from a database and creating the list of nodes. Is there a way to get the method to execute quicker? Perhaps using parallel task library?
Each node looks like this:
public class Node : INode
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string DisplayText { get; set; }
public bool DefaultState { get; set; }
public List<Node> ChildItems { get; set; }
}
The fastest implementation I have been able to come up with has been just two for
loops using recursion:
/// <summary>
/// For loop incrementing: 00:00:28.2218157
/// </summary>
/// <param name="folderRepo"></param>
/// <param name="folders"></param>
private void GetChildFoldersIncrement(IRepository<Folder> folderRepo, List<Node> folders)
{
for (var i = 0; i < folders.Count; i++)
{
var folderId = folders[i].Id;
var childFolders = folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToList();
if (childFolders.Count == 0) continue;
for (var j = 0; j < childFolders.Count; j++)
{
var node = new Node
{
Id = childFolders[j].FolderID,
ParentId = childFolders[j].ParentFolderID,
DisplayText = childFolders[j].FolderName,
DefaultState = false,
ChildItems = new List<Node>()
};
if (folders[i].ChildItems == null) folders[i].ChildItems = new List<Node>();
folders[i].ChildItems.Add(node);
}
if (folders[i].ChildItems.Count > 0) GetChildFoldersIncrement(folderRepo, folders[i].ChildItems);
}
}
I've attempted to optimize the loops by decrementing them but it was actually slightly slower:
/// <summary>
/// For loop decrement: 00:00:28.3496396
/// </summary>
/// <param name="folderRepo"></param>
/// <param name="folders"></param>
private void GetChildFoldersDecrement(IRepository<Folder> folderRepo, List<Node> folders)
{
if (folders == null) return;
var maxFolders = folders.Count();
for (var i = maxFolders - 1; i >= 0; --i)
{
var folderId = folders[i].Id;
var childFolders = folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToList();
var maxChildFolders = childFolders.Count();
for (var j = maxChildFolders - 1; j >= 0; --j)
{
var node = new Node
{
Id = childFolders[j].FolderID,
ParentId = childFolders[j].ParentFolderID,
DisplayText = childFolders[j].FolderName,
DefaultState = false,
ChildItems = new List<Node>()
};
if (folders[i].ChildItems == null) folders[i].ChildItems = new List<Node>();
folders[i].ChildItems.Add(node);
}
GetChildFoldersDecrement(folderRepo, folders[i].ChildItems);
}
}