首页 > 解决方案 > 如何查找特定类别 id c# 的分层树最后一个节点

问题描述

        List<Categories> categories = new List<Categories>
        {
            new Categories { CatID = 1, CatName = "Computer, IT & Networking"},
            new Categories { CatID = 2, CatName = "Computer & Servers"},
            new Categories { CatID = 3, CatName = "Desktop PCs"},
            new Categories { CatID = 4, CatName = "Servers"},
            new Categories { CatID = 5, CatName = "Computer Parts & Components"},
            new Categories { CatID = 6, CatName = "Harddrive"},
            new Categories { CatID = 7, CatName = "CPUs"},
            new Categories { CatID = 8, CatName = "Electronics"},
            new Categories { CatID = 9, CatName = "Furniture"},
            new Categories { CatID = 10, CatName = "RAM"},
            new Categories { CatID = 11, CatName = "Harddrive"},
            new Categories { CatID = 12, CatName = "Workbooks"},
            new Categories { CatID = 13, CatName = "IBM Desktop"},
            new Categories { CatID = 14, CatName = "HP Desktop"}
        };

        List<CategoriesMapping> categoriesMapping = new List<CategoriesMapping>
        {
            new CategoriesMapping { CategoriesMappingID = 1, CatID = 1, MapCatID = 2},
            new CategoriesMapping { CategoriesMappingID = 2, CatID = 1, MapCatID = 5},
            new CategoriesMapping { CategoriesMappingID = 3, CatID = 2, MapCatID = 3},
            new CategoriesMapping { CategoriesMappingID = 4, CatID = 2, MapCatID = 4},
            new CategoriesMapping { CategoriesMappingID = 5, CatID = 5, MapCatID = 6},
            new CategoriesMapping { CategoriesMappingID = 6, CatID = 5, MapCatID = 7},
            new CategoriesMapping { CategoriesMappingID = 7, CatID = 5, MapCatID = 10},
            new CategoriesMapping { CategoriesMappingID = 8, CatID = 5, MapCatID = 11},
            new CategoriesMapping { CategoriesMappingID = 9, CatID = 2, MapCatID = 12},
            new CategoriesMapping { CategoriesMappingID = 10, CatID = 3, MapCatID = 13},
            new CategoriesMapping { CategoriesMappingID = 11, CatID = 3, MapCatID = 14}
        };

如何获取特定 CatID 的最后一个节点,例如在上面的代码中,如果我选择 CatID = 2,它应该只带回 CatID 4、12、13、14。它不应该返回其子类别 CatID 3,因为它也有 13 和 14 的节点。相反,它只返回 CatID 3 的子节点。

标签: c#categories

解决方案


我假设您正在尝试使用 linq 魔法来解决这个问题。不幸的是,在Jon Skeet 的这个答案中,您可以看到它非常不方便。

你可以试试这样的东西但它会变得相当昂贵。

我的建议是创建一个新功能,例如

   public List<int> GetNoDescendateCategoriesCategoryId(int categoryId) {
       List<int> newCategories = new List<int>();
       List<int> childCategories = this.categoriesMapping.Where(m => m.CatID == categoryId).Select(x=> x.MapCatID).ToList();

       if(childCategories.Count == 0) {
          return new List<int>() {categoryId};
       }
       foreach (int catId in childCategories ) {
          newCategories.AddRange(GetNoDescendateCategoriesCategoryId(catId));
       }
       return newCategories;
   }

您可以查看https://dotnetfiddle.net/1IbjOf作为示例。


推荐阅读