遍历转树结构

遍历转树结构
{

    var list = new List<Foo>{
    new Foo("111",1),
    new Foo("112",2),
    new Foo("113",2),
    new Foo("114",2),
    new Foo("115",3),
    new Foo("116",1),
    new Foo("117",1),
    new Foo("118",2),
    new Foo("119",3),
    new Foo("120",4),

};
    var result = new List<Far>();

    foreach (var item in list)
    {
        if (result.Count == 0)
        {
            result.Add(new Far(item.Id, item.Layer, null));
            continue;
        }

        var temp = result.Last();

        while (true)
        {
            if (temp == null)
            {
                result.Add(new Far(item.Id, item.Layer, temp));
                break;
            }
            if (temp.Layer == item.Layer - 1)
            {
                temp.Children.Add(new Far(item.Id, item.Layer, temp));
                break;
            }

            if (temp.Layer == item.Layer)
            {
                if (temp.Parent == null)
                    result.Add(new Far(item.Id, item.Layer, null));

                else
                    temp.Parent.Children.Add(new Far(item.Id, item.Layer, null));

                break;
            }

            temp = temp.Children.LastOrDefault();
        }

    }
    Console.WriteLine("");
}

class Far
{
    public string Id { get; set; }
    public int Layer { get; set; }
    public Far Parent { get; set; }
    public List<Far> Children { get; set; }

    public Far(string id, int layer, Far parent)
    {
        Id = id;
        Layer = layer;
        Parent = parent;
        Children = new List<Far>();
    }
}


class Foo
{
    public string Id { get; set; }
    public int Layer { get; set; }

    public Foo(string id, int layer)
    {
        Id = id;
        Layer = layer;
    }
}
posted @ 2024-01-29 21:47  Bo-Hong  阅读(4)  评论(0编辑  收藏  举报