c# - 从树或列表层次结构中查找对象

标签 c# linq recursion

我正在上一些课

public class Employee
{
    public Employee[] ChildOrg{get; set;}
    public string name {get; set;};
    public string id{get; set;};
}

我如何从其 ID 中找到特定员工?

我尝试使用以下功能。

private static Employee GetNode(Employee objEmployeeList, string id)
{
    if (objEmployeeList.ChildOrg==null)
    {
        return null;
    }
    foreach (var item in objEmployeeList.ChildOrg)
    {
        if (item.ID.Equals(id))
        {
            return (objEmployeeList)item;
        }
    }
    foreach (var item in objEmployeeList.ChildOrg)
    {
        return GetNode((objEmployeeList)item, id);
    }
    return null;
}

如您所见,我正在尝试编写一些递归函数来获取员工。

如果你仔细看,它只会到达第一个节点的底部。

然后它返回 null 并且不去任何其他节点。

请告诉我如何使用 linq 更正我的功能以及其他方法来完成同样的事情?

编辑:-

我想访问特定节点及其兄弟节点。

最佳答案

类(class)的一些变化和套路的一些变化。

public class Employee
{
    public List<Employee> ChildOrg { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }

    public Employee(string id, string name)
    {
        Id = id;
        Name = name;
        ChildOrg = new List<Employee>();
    }

    public Employee AddChildOrg(string id, string name)
    {
        var newEmployee = new Employee(id, name);
        ChildOrg.Add(newEmployee);
        return newEmployee;
    }

    public static Employee GetNode(Employee father, string id)
    {
        if (father != null)
        {
            if (father.Id.Equals(id))
                return father;


            if (father.ChildOrg != null)
                foreach (var child in father.ChildOrg)
                {
                    if (child.Id.Equals(id))
                        return child;

                    var employee = Employee.GetNode(child, id);

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

还有一个小测试程序:

class Program
{
    static void Main(string[] args)
    {
        Employee root = new Employee(1.ToString(), "root");
        var e2 = root.AddChildOrg(2.ToString(), "2 second level");
        var e3 = e2.AddChildOrg(3.ToString(), "3 third level");
        var e1 = root.AddChildOrg(4.ToString(), "4 second level");
        var e5 = e1.AddChildOrg(5.ToString(), "5 third level");

        Console.WriteLine("Id 3 -> {0}", Employee.GetNode(root, "3").Name);
        Console.WriteLine("Id 1 -> {0}", Employee.GetNode(root, "1").Name);
        Console.WriteLine("Id 5 -> {0}", Employee.GetNode(root, "5").Name);
        Console.ReadKey();
    }
}

关于c# - 从树或列表层次结构中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27424580/

相关文章:

c# - 遍历子元素,找到一些东西并访问它的兄弟属性

java - 如何递归计算数字的平均值

c++ - 基础C++递归程序题

c# - X509 找不到请求的对象

c# - 为什么通过 ASP.NET 方法运行查询比 native SQL 花费更长的时间?

c# - LINQ 从每个查询中获取第一行

c++ - 间接递归,依赖静态变量

c# - Monotouch UITableViewCell AddSubView

c# - 使用 C# LINQ 按任一列分组

c# - LINQ 多对多计数分组