I fetch a bunch of categories for a DropDown
tree, and have to implement search in this dropdown. If there is a match in one of the elements, it should also get all parents to display in the dropdown hierarchy. The number of childnodes is unknown, and can be changed at any given time (example has only 3 levels but can be 5 also).
The search applies on every ScrapCategory description.
I get the expected result but I would love to see this in \$O(N)\$.
public sealed class ScrapCategory
{
public int Id { get; set; }
public bool IsActive { get; set; }
public string Description { get; set; }
public int Level { get; set; }
public int ParentId { get; set; }
}
public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)
{
var result = new List<ScrapCategory>();
foreach (ScrapCategory category in categories)
{
if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
result.Add(category);
if (category.ParentId > 0)
{
int parentId = category.ParentId;
while (parentId > 0)
{
var parent = categories.Where(x => x.Id == parentId)?.First();
if (!result.Contains(parent))
result.Add(parent);
parentId = parent.ParentId;
}
}
}
return result.OrderBy(x => x.Level).ToArray();
}