繁体   English   中英

如何从 C# 中的这个分层父子结构中找到任何项目

[英]How to find any item from this Hierarchical Parent-Child Structure in C#

如何从列表中找到任何项目,因为它是动态的,它可能在列表的任何 position 的父项或子项中,并且需要在子项列表为 0 时停止查找,下面是列表的 Model 和和分层父子结构示例

例子:-

父->子->子->子或父->子->子->子->子->子->子

public class Child
    {
        public string key { get; set; }
        public string title { get; set; }
        public string parent_Category { get; set; }
        public List<Child> children { get; set; }
    }

    public class Parent
    {
        public string key { get; set; }
        public string title { get; set; }
        public string parent_Category { get; set; }
        public List<Child> children { get; set; }
    }

您可以进行递归搜索,例如:

Child SearchChild(string title, Child c)
{
    if (c.title == title)
    {
        return c;
    }
    return SearchAmongChildren(title, c.children);
}

Child SearchAmongChildren(string title, List<Child> children)
{
    foreach (var c in children)
    {
        if (c.title == title)
        {
            return c;
        }

        if (c.children != null)
        {
            var _c = SearchAmongChildren(title, c.children);

            if (_c != null)
                return _c;
        }
    }

    return null;
}

然后,开始搜索:

var theChildThatIWant = SearchAmongChildren("the title that I want", parent.children);

var theChildThatIWant = SearchChild("the title that I want", child);

if (theChildThatIWant == null)
{
    throw new ChildNotFoundException("Sorry, the child that you're looking for is not available.");
}

您可以使用 BFS 或 DFS 搜索。

bool Exist(Parent parent, string key)
{
    if (parent.key == key) return true;

    if (parent.children == null) return false;
    var queue = new Queue<Child>(parent.children);
    while (queue.Any())
    {
        Child c = queue.Dequeue();
        bool match = c.key == key;
        if (match) return true;

        if (c.children == null) continue;
        foreach (Child grandChild in c.children)
        {
            queue.Enqueue(grandChild);
        }
    }

    return false;
}

// 测试场景

Parent parent1 = new Parent();
var result1 = Exist(parent1, "key-1");
Console.WriteLine($"Actual : {result1}, Expected : False");

Parent parent2 = new Parent { children = new List<Child> { new Child() { key = "key-1" }, new Child() { key = "key-2" } } };
var result2 = Exist(parent2, "key-2");
Console.WriteLine($"Actual : {result2}, Expected : True");

Parent parent3 = new Parent { children = new List<Child> { new Child() { key = "key-1" }, new Child() { key = "key-2", children = new List<Child> { new Child() { key = "key-5" } } } } };
var result3 = Exist(parent3, "key-5");
Console.WriteLine($"Actual : {result3}, Expected : True");

var result4 = Exist(parent3, "key-21323");
Console.WriteLine($"Actual : {result4}, Expected : False");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM