Linq到xml的后代

时间:2010-12-17 19:11:29

标签: c# linq recursion linq-to-xml linq-to-objects

如何使用linq对包含相同对象X级深度的子​​集合的对象集合获取doc.Descendants()的类似功能?

最后一个嵌套集合包含需要获取的数据,所有其他父集合仅仅是分组。我可以将集合转换为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的子列表。嵌套级别可以根据数据的设置方式而有所不同,所以我永远不知道有多少级别。最底部的列表将具有Type =“Model”,而每个列表优先级将具有Type =“Series”,从而产生如下内容:

Series1
   Series2
      Series3
          Model1
          Model1
   Series2
      Model3
      Model4

2 个答案:

答案 0 :(得分:2)

使用此Node class,解决方案非常简单。

将ProductLineClass更改为litte:

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

答案 1 :(得分:0)

您可以使用Linq的SelectMany功能。

IEnumerable<ProductLine> products = <something>;
IEnumerable<ProductLine> modelProducts = products
    .SelectMany((x) => x.Children)

然而,这只会趋于一个深度。您需要查看Recursive SelectMany才能获得完整效果。请参阅以下链接以获取更多建议。

相关问题