2010-12-17 99 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);