Linq for xml descendants

How can I get similar functionality for doc.Descendants () using linq to collection objects containing deep X-level struts of the same objects?

The last nested collection contains the data you need to retrieve, and all other parent collections are just groupings. I could convert the collection to XDocument and call the descendant function, but I would rather simulate this functionality against this collection of objects.

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

I can have a ProductLine list that contains child lists of ProductLine. Nested levels may vary depending on how the data was configured, so I never know how many levels exist. The bottommost list will have Type = "Model", while each previous list will have Type = "Series", which will lead to something like:

Series1
   Series2
      Series3
          Model1
          Model1
   Series2
      Model3
      Model4
+3
source share
2 answers

Using this Node class, the solution is quite simple.

Change ProductLineClass to one bit:

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

Create a tree:

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 all the necessary information:

// 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);
+2
source

You can use the Linq function SelectMany.

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

. SelectMany . . .

0

Source: https://habr.com/ru/post/1780925/


All Articles