Linq to XML的后代元素

3

如何在使用包含多层子集合的对象集合时,通过linq获得与doc.Descendants()类似的功能?

需要获取的数据包含在最后一个嵌套集合中,所有其他父级集合只是分组。 我可以将集合转换为XDocument并调用descendants函数,但我更喜欢针对此对象集合模拟该功能。

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

我可以有一个包含子产品线列表的产品线列表。嵌套级别可以根据数据设置的方式而变化,因此我永远不知道有多少级别。最底层的列表将具有Type =“Model”,而之前的每个列表将具有Type =“Series”,从而产生以下内容:

Series1
   Series2
      Series3
          Model1
          Model1
   Series2
      Model3
      Model4

http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/fe3d441d-1e49-4855-8ae8-60068b3ef741/ - Jahan Zinedine
2个回答

2
使用这个节点类,解决方案就非常简单了。
稍微修改一下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);

0
你可以使用 Linq 的 SelectMany 函数。
IEnumerable<ProductLine> products = <something>;
IEnumerable<ProductLine> modelProducts = products
    .SelectMany((x) => x.Children)

然而,这只会将其展平到一层深度。您需要查看递归SelectMany以获得完整效果。请参阅以下链接获取更多建议。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接