2010-12-17 92 views
3

如何使用linq針對包含相同對象的子集合的對象集合獲取與doc.Descendants()相似的功能?Linq to xml後代

最後一個嵌套集合包含需要獲取的數據,所有其他父集合僅僅是分組。我可以將集合轉換爲XDocument並調用後代函數,但我寧願模仿該對象集合的功能。

public class ProductLine 
{ 
    public string Id {get;set;} 
    public string ParentId {get;set;} 
    public string Name {get;set;} 
    public string Type {get;set;} 
    public string Level {get;set;} 
    public IEnumerable<ProductLine> Children {get;set;} 
} 

我可以有一個ProductLine列表,其中包含ProductLine的子列表。嵌套的級別可以根據數據的設置而有所不同,所以我不知道有多少級別。最底層的名單將有一個類型=「模式」,而每一個名單之前將有一個類型=「系列」造成這樣的:

Series1 
    Series2 
     Series3 
      Model1 
      Model1 
    Series2 
     Model3 
     Model4 
+0

http://social.msdn.microsoft .COM /論壇/ EN-US/linqprojectgeneral /線程/ fe3d441d-1e49-4855-8ae8-60068b3ef741 / – 2010-12-17 21:06:58

回答

2

有了這個Node class,該解決方案是很容易的。

更改ProductLineClass豆蔻位:

public class ProductLine 
{ 
    public int Id { get; set; } 
    public int? ParentId { get; set; } 
    public string Name { get; set; } 
    public string Type { get; set; } 
    // The level property is no longer needed because it is a property of the Node class 
    public IEnumerable<ProductLine> Children { get; set; } 
} 

創建樹:

var productlinesInAFlatList = GetListOfproductLines(); 

// Create alle the trees that can me made with the flad list based on Id and ParentId's 
var rootNodes = Node<ProductLine>.CreateTree(productlinesInAFlatList, p => p.Id, p => p.ParentId); 

// Assume there is only one tree in this flat ist 
var rootNode = rootNodes.Single(); 

獲得您所需要的所有信息:

// Get the nodes that has no childnodes 
var nodesWithoutChildNodes = rootNode.Descendants.Where(n => !n.Descendants.Any()); 

// If you just want the values of this childnodes 
var values = nodesWithoutChildNodes.Values(); 

// When you need the levels of the values 
var levels = nodesWithoutChildNodes.Select(n => n.Level);