| | | 1 | | using ConsoleApp1; |
| | | 2 | | using TreeGrouping.Application.DbService; |
| | | 3 | | using TreeGrouping.Application.DbService.Models; |
| | | 4 | | |
| | | 5 | | namespace TreeGrouping.Application.CategoryService; |
| | | 6 | | |
| | | 7 | | public class CategoryTreeService |
| | | 8 | | { |
| | | 9 | | public List<CategoryModel> BuildTree(List<CategoryModel> categories) |
| | | 10 | | { |
| | 15 | 11 | | var lookup = categories.ToLookup(c => c.ParentId); |
| | | 12 | | |
| | | 13 | | List<CategoryModel> BuildBranch(int? parentId) => |
| | 18 | 14 | | lookup[parentId] |
| | 27 | 15 | | .Select(c => new CategoryModel |
| | 27 | 16 | | { |
| | 27 | 17 | | Id = c.Id, |
| | 27 | 18 | | ParentId = c.ParentId, |
| | 27 | 19 | | Name = c.Name, |
| | 27 | 20 | | ParentName = c.ParentName, |
| | 27 | 21 | | Children = c.Children.Any() ? c.Children : BuildBranch(c.Id), |
| | 27 | 22 | | IsFiltred = c.IsFiltred, |
| | 27 | 23 | | LinkId = c.LinkId, |
| | 27 | 24 | | Links = c.Links, |
| | 27 | 25 | | CatChar = c.CatChar, |
| | 27 | 26 | | Translation = c.Translation, |
| | 27 | 27 | | }).ToList(); |
| | | 28 | | |
| | 5 | 29 | | return BuildBranch(null).Concat(BuildBranch(0)).ToList(); |
| | | 30 | | } |
| | | 31 | | |
| | | 32 | | |
| | | 33 | | public async Task<List<CategoryModel>> CategoryLinkToModel(IDatabaseService dbService, List<CategoryModel> tree, Lis |
| | | 34 | | { |
| | 24 | 35 | | foreach (var link in links) |
| | | 36 | | { |
| | 6 | 37 | | if (!Enum.TryParse<CategoryLinkType>(link.LinkTypeName, true, out var linkType)) |
| | | 38 | | continue; |
| | | 39 | | |
| | 5 | 40 | | var linkTreeTask = await dbService.ExecuteStoredProcedureAsync(linkType.GetProcedureType(), link.LinkCategor |
| | 10 | 41 | | var linkCategory = linkTreeTask.FirstOrDefault(lc => lc.Id == link.LinkCategoryId); |
| | | 42 | | |
| | 10 | 43 | | var treeItem = tree.FirstOrDefault(tr => tr.Id == link.CtCategoryId); |
| | 5 | 44 | | if (treeItem != null && linkCategory != null) |
| | | 45 | | { |
| | 4 | 46 | | bool linkExists = treeItem.Links.Any(l => l.Id == link.Id); |
| | 3 | 47 | | if (!linkExists) |
| | | 48 | | { |
| | 2 | 49 | | treeItem.Links.Add(new Link |
| | 2 | 50 | | { |
| | 2 | 51 | | CategoryLinkType = linkType, |
| | 2 | 52 | | CategoryId = linkCategory.Id, |
| | 2 | 53 | | Id = link.Id |
| | 2 | 54 | | }); |
| | | 55 | | } |
| | | 56 | | |
| | 3 | 57 | | treeItem.ParentName ??= link.LinkTypeName; // только если ещё не установлено |
| | | 58 | | } |
| | 5 | 59 | | } |
| | | 60 | | |
| | 6 | 61 | | return tree; |
| | 6 | 62 | | } |
| | | 63 | | } |