gpt4 book ai didi

c# - 重构函数,使其为 O(N)

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:49 26 4
gpt4 key购买 nike

我为下拉树获取了一堆类别,并且必须在这个下拉列表中实现搜索。如果其中一个元素匹配,它还应该让所有父元素显示在下拉层次结构中。

我从 2 个 foreach 循环开始,在其中过滤掉匹配项,在一个循环中检查 parentId 的匹配项并递归添加父项直到没有剩余( parentId == 0).

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)
continue;

ScrapCategory currentParent = categories.Where(x => x.Id == category.ParentId).First();

if (!result.Contains(currentParent))
result.Add(currentParent);

while (currentParent?.ParentId > 0)
{
currentParent = categories.Where(x => x.Id == currentParent.ParentId)?.First();
if (!result.Contains(currentParent))
result.Add(currentParent);
}
}

return result.OrderBy(x => x.Level).ToArray();
}

我得到了预期的结果,但我希望在 O(N) 中看到这个结果,因此只有 categories 没有那些 .Where() 子句的交互。

编辑:我设法去掉了一个 .Where() 子句。

 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();
}

最佳答案

这是我的最终结果,我很满意。

public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)
{
var lookup = categories.ToDictionary(category => category.Id);
var result = new HashSet<ScrapCategory>();
foreach (ScrapCategory category in categories)
{
if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
result.Add(category);
int parentId = category.ParentId;
while (parentId > 0)
{
ScrapCategory parent = lookup[parentId];
if (!result.Add(parent))
break;
parentId = parent.ParentId;
}
}
return result.OrderBy(n => n.Level).ToArray();
}

关于c# - 重构函数,使其为 O(N),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com