Skip to main content
 首页 » 编程设计

c#之如何使用Linq遍历父子数据

2024年02月13日24bhlsheji

我有一个具有以下结构的类:

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

从这个集合 categories(有 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 

请您参考如下方法:

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

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