【问题标题】:How to search Hierarchical Data with Linq in list如何在列表中使用 Linq 搜索分层数据
【发布时间】:2022-01-24 14:50:11
【问题描述】:

经销商注册。

我想在列表中填写有关经销商的以下信息

Id
ParentId
Name

对于每个经销商,必须确定经销商在系统中注册的推荐人。这可以是任何已经在系统中注册的人——在这种情况下,他们必须从已注册的经销商列表中选择,或者推荐人信息可以是空白的,这意味着经销商在没有推荐人的情况下在系统中注册。每个经销商最多可以推荐三个人,系统应确保不超过三个人在同一经销商“下”注册。另外,上述经销商的层级深度应该最大为5级——也就是说,经销商可以带一个人推荐,他也会带一个人带他的推荐,等等。最多5个级别。因此,在这样的组中,总共可以有 1 + 3 + 9 + 27 + 81 = 121 人。系统必须提供对给定级别的控制。

【问题讨论】:

  • 嗨!欢迎来到堆栈溢出。请发布您已经尝试过的代码,以便我们更好地为您提供帮助。
  • 你的意思是你想用 LINQ 枚举一棵树吗?

标签: c# list linq


【解决方案1】:

您可以使用递归来查找列表中任何元素的深度,并使用普通的旧计数来查找引用者的数量。

以下代码是该想法的实现。

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

【讨论】:

    猜你喜欢
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多