以自下而上的方法解析嵌套对象结构

本文关键字:嵌套 对象 结构 自下而上 方法 | 更新日期: 2023-09-27 18:29:00

public class Group
{
    public int ID;
    public bool Earned;
    public bool Available;
    public List<Group> ChildGroups;
    public List<Item> ChildItems;
}
public class Item
{
    public int ID;
    public bool Earned;
    public bool Available;
}
public class Evaluator
{
    public List<Group> FindEarned(Group source)
    {
        //Filter implementation
        foreach (Group grp in source.Groups)
        {
            grp.Items = grp.Items.Where(
                                        x => x.Earned == true).ToList();
            if (grp.Groups != null && grp.Groups.Count > 0)
            {
                grp.Groups = FilterEarned(grp);
            }
            else
            {
            }
        }
        return source.Groups;
    }
}

我的查找获得方法应返回任何子组或项目处于赢得状态的组列表。例:

Group1 - Pending
  -Group11 -pending
  -Group12 -pending
  -Group13 -Pending
  -Item11 -Pending
  -Item12 -Pending
 Group2
  -Group21 -pending
  --Group211 -pending
  ---Item2111 - earned 
  -Group22 -pending
  -Group23 -Pending
  -Item21 -Pending
  -Item22 -Pending

方法应返回

 Group2
  -Group21 -pending
  --Group211 -pending
  ---Item2111 - earned 

以自下而上的方法解析嵌套对象结构

我不确定我是否正确,但如果您需要过滤掉所有未获得的项目和组,您可以使用此扩展方法。它不是很脆弱,因为它必须计算 Earn = true 的孩子,并且它还会创建新组,否则您的初始数据将被损坏。

    public static IEnumerable<Group> EarnedGroups(this IEnumerable<Group> data)
    {
        foreach (var group in data)
        {
            var items = group.ChildItems.Where(x => x.Earned).ToList();
            var groups = group.ChildGroups.EarnedGroups().ToList();
            if (items.Count > 0 || groups.Count > 0 || group.Earned)
                yield return new
                        Group
                        {
                            ID = group.ID,
                            Available = group.Available,
                            Earned = group.Earned,
                            ChildItems = items,
                            ChildGroups = groups
                       };
        }
    }