如何使用Linq遍历父子数据

时间:2014-04-21 14:14:59

标签: c# asp.net-mvc linq

我有一个具有以下结构的课程:

public class OilCategory 
{
    public OilCategory Parent { get; set; } // For representing parent
    public string Name { get; set; }
    public int Position { get; set; }
    public int Id { get; set; }
}

我有OilCategories的列表集合:

OilCategory rootCategory = new OilCategory {Id = 1, Name = "Root", Position = 1, Parent = null};
OilCategory firstLevel1  = new OilCategory {Id = 2, Name = "fl-1", Position = 1, Parent = rootCategory};
OilCategory firstlevel2  = new OilCategory {Id = 3, Name = "fl-2", Position = 2, Parent = rootCategory};

OilCategory secondLeve1  = new OilCategory {Id = 4, Name = "sl-1", Position = 1, Parent = firstLevel1};
OilCategory secondlevel2 = new OilCategory {Id = 5, Name = "sl-2", Position = 2, Parent = firstLevel1};

List<OilCategory> categories=new List<OilCategory>();
;
categories.Add(rootCategory);
categories.Add(firstLevel1);
;categories.Add(firstlevel2);
categories.Add(secondLeve1);
categories.Add(secondlevel2);

从这个集合类别(有5个类别,有或没有高级父级),我如何生成如下结构{root / child / child /}之类的项目:

Id            ItemName

1              root
2              root /fl-1
3              root /fl-2
4              root /fl-1/sl-1
5              root /fl-1/sl-1

1 个答案:

答案 0 :(得分:4)

从一个方法开始,生成一个项目序列及其所有祖先:

public IEnumerable<OilCategory> Ancestors
{
    get
    {
        OilCategory current = this;
        while (current != null)
        {
            yield return current;
            current = current.Parent;
        }
    }
}

然后只需将序列反转为自上而下而非自下而上排序并将它们连接在一起。

public string ItemName
{
    get
    {
        return string.Join("/",
            Ancestors.Reverse().Select(category => category.Name));
    }
}