Sormita Chakraborty Sormita Chakraborty - 1 year ago 114
C# Question

C# linq hierarchical list property set

I have the following class:

public class Products
public int ID { get; set; }
public int KeyID { get; set; }
public int KeyLevel { get; set; }
public string COMBasis { get; set; }

Here ID is the primary key and KeyID contains the parent ID of the item. KeyLevel contains the level of the node in the hierarchical tree. I have to set the COMBasis property for all the children if the parent's property is changed. How can I get the children?

Following is what I am already doing but I am stuck in the after KeyLevel part:

foreach (Products prod in ProductList.Where(x => x.KeyID == prd.ID))
prod.COMStandard = prd.COMStandard;

Answer Source

So you just need to put that in a recursive function. Something like this:

void ApplyCOMBasis(List<Products> productList, int pId, string comStandard)
    foreach (Products prod in productList.Where(x => x.KeyID == pId))
        prod.COMStandard = comStandard;
        ApplyCOMBasis(productList, prod, comStandard);

Which you can then call like this (based on your current code):

ApplyCOMBasis(ProductList, prd.ID, prd.COMBasis);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download