Home > OS >  How to search Hierarchical Data with Linq in list
How to search Hierarchical Data with Linq in list

Time:12-24

Distributor Registration.

I want to fill list with following information about the distributor

Id
ParentId
Name

For each distributor, it must be determined on whose recommendation the distributor is registered in the system. This can be anyone already registered in the system - in which case they must be selected from a list of already registered distributors, or the referrer information can be blank, which means that the distributor registers in the system without a recommender. Each distributor can bring up to three people on its recommendation, the system should ensure that no more than three people are registered "under" the same distributor. Also, the depth of the hierarchy of the mentioned distributors should be maximum 5 - that is, the distributor can bring a person with a recommendation, who will also bring a person with his recommendation, etc. Maximum 5 levels. Accordingly, in such a group there can be a total of 1 3 9 27 81 = 121 people. The system must provide control over the given levels.

CodePudding user response:

You can use recursion to find the depth of any element in the list and a plain old count to find the number of referrers.

The following code is an implementation of that idea.

void Main()
{
    var distributors = new List<Distributor> {
        new Distributor { Id =  1, ParentId =  0, Name = "A" },
        new Distributor { Id =  7, ParentId =  1, Name = "B" },
        new Distributor { Id =  9, ParentId =  7, Name = "C" },
        new Distributor { Id = 13, ParentId =  9, Name = "D" },
        new Distributor { Id = 28, ParentId = 13, Name = "E" },
    };

    var valid = IsValidToAdd(distributors, 9);
    
    Console.WriteLine(valid);
}

public bool IsValidToAdd(List<Distributor> distributors, int parentId)
{
    var referCount = distributors.Count(d => d.ParentId == parentId);
    Console.WriteLine($"refer:{referCount}");
    if (referCount == 3)
    {
        Console.WriteLine("There are already 3 referals for this parent");
        return false;
    }

    var level = GetLevel(distributors, parentId);
    Console.WriteLine($"level: {level}");
    if (level > 5)
    {
        Console.WriteLine("There are already 5 levels of referals");
        return false;
    }
    
    return true;
}

public int GetLevel(List<Distributor> distributors, int parentId)
{
    var parent = distributors.FirstOrDefault(d => d.Id == parentId);

    if (parent == null)
    {
        return 1;
    }

    return 1   GetLevel(distributors, parent.ParentId);
}

public class Distributor
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
}
  • Related