我正在尋找將數據從平面列表轉換爲層次結構。我怎樣才能以可讀的方式來完成這個工作,但在性能上仍然可以接受,並且我可以利用任何.NET庫。我認爲這被認爲是某些術語(在這種情況下由行業)的「方面」。將平面陣列中的數據轉換爲層次結構
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public Industry Industry { get; set; }
}
public class Industry
{
public int IndustryId { get; set; }
public string IndustryName { get; set; }
public int? ParentIndustryId { get; set; }
public Industry ParentIndustry { get; set; }
public ICollection<Industry> ChildIndustries { get; set; }
}
現在讓我們假設我有一個List<Company>
,我期待將其改造成一個List<IndustryNode>
//Hierarchical data structure
public class IndustryNode
{
public string IndustryName{ get; set; }
public double Hits { get; set; }
public IndustryNode[] ChildIndustryNodes{ get; set; }
}
這樣得到的對象應該是這樣的下面後,序列化:
{
IndustryName: "Industry",
ChildIndustryNodes: [
{
IndustryName: "Energy",
ChildIndustryNodes: [
{
IndustryName: "Energy Equipment & Services",
ChildIndustryNodes: [
{ IndustryName: "Oil & Gas Drilling", Hits: 8 },
{ IndustryName: "Oil & Gas Equipment & Services", Hits: 4 }
]
},
{
IndustryName: "Oil & Gas",
ChildIndustryNodes: [
{ IndustryName: "Integrated Oil & Gas", Hits: 13 },
{ IndustryName: "Oil & Gas Exploration & Production", Hits: 5 },
{ IndustryName: "Oil & Gas Refining & Marketing & Transporation", Hits: 22 }
]
}
]
},
{
IndustryName: "Materials",
ChildIndustryNodes: [
{
IndustryName: "Chemicals",
ChildIndustryNodes: [
{ IndustryName: "Commodity Chemicals", Hits: 24 },
{ IndustryName: "Diversified Chemicals", Hits: 66 },
{ IndustryName: "Fertilizers & Agricultural Chemicals", Hits: 22 },
{ IndustryName: "Industrial Gases", Hits: 11 },
{ IndustryName: "Specialty Chemicals", Hits: 43 }
]
}
]
}
]
}
其中「命中」是屬於該組的公司數量。
爲了澄清,我需要一個List<Company>
轉換成List<IndustryNode>
不序列化List<IndustryNode>
你是什麼意思的效率?最具可讀性和可維護性或最佳性能? – CookieOfFortune
對不起,我沒有說清楚。它需要有效,但我願意爲可讀性和可維護性做一些折衷 – parliament
最終它將被序列化 – parliament