2017-05-31 145 views
1

我有以下2所列出两个列表类别和子类别

- `List<Category>` 
- `List<SubCategory>` 

     public class Category 
     { 
      public string CategoryId 
      { 
       get; 
       set; 
      } 

      public List<SubCategory> subCategories 
      { 
       get; 
       set; 
      } 


    public string Name 
{ 
get; 
set; 
} 
     } 


     public class SubCategory 
     { 
      public string SubCategoryId 
      { 
       get; 
       set; 
      } 
      public string CategoryId 
      { 
       get; 
       set; 
      } 
      public string Name 
      { 
       get; 
       set; 
      } 
     } 
  1. 我想找到两个类别和子类别匹配的类别(按类别编号)。

  2. 将具有特定CategoryId的所有子类别添加到具有与CategoriesList相同的CategoryId的Category类别的subCategories数组中。

到目前为止我已经尝试过。

var categories = Categories.Select(c => c.Id); 

      foreach(Guid categoryId in categories) 
      { 
       var subCategoriesByCategoryId = validatedSubCategories.Where(subCats => subCats.CategoryId == categoryId); 
       List<SubCategory> subCategories = new List<SubCategory>(); 
       foreach(SubCategory subCategory in subCategoriesByCategoryId) 
       { 
        subCategories.Add(subCategory); 
       } 

       if (subCategories.Count() > 0) 
       { 
var categoryById = Categories.FirstOrDefault(vC => vC.Id == categoryId); 
if (categoryById != null) categoryById.SubCategories = subCategories; 
       } 
      } 

我该如何做到这一点?

示例数据

Category cat1= new Category {CategoryId=1}; 
Category cat2= new Category {CategoryId=2}; 
Category cat3= new Category {CategoryId=3}; 
Category cat4= new Category {CategoryId=4}; 

List<Category > Categories = new List<Category >() 
Categories.Add(cat1); 
Categories.Add(cat2); 
Categories.Add(cat3); 
Categories.Add(cat4); 

SubCategory sc1 = new SubCategory {CategoryId=1); 
SubCategory sc2 = new SubCategory{CategoryId=2}; 
SubCategory sc3 = new SubCategory{CategoryId=3}; 
SubCategory sc4 = new SubCategory{CategoryId=4}; 

List<SubCategory> SubCategories = new List<SubCategory >() 
SubCategories.Add(sc1); 
SubCategories.Add(sc1); 
SubCategories.Add(sc3); 
SubCategories.Add(sc4); 

期望输出是从与类别ID 1子类别

2子类别的项目应被添加到具有类别ID 1在所属分类从子类别与

1子类别项目的类别项目CategoryId 3应添加到CategoryList中具有CategoryId 3的Category项目

1 Subcate从类别编号4小类血淋淋的项目应该被添加到其类别编号4类别项所属分类

+1

你尝试过这么远吗?你能告诉我们一些代码吗?你也可以共享一个[mcve](https://stackoverflow.com/help/mcve)(例如在.NETFiddle上)? – aloisdg

+0

会很好,如果你有一个样本数据和预期的输出 –

回答

1

试试下面的语句:

List<Category> categories = new List<Category>(); 
List<SubCategory> subCategories = new List<SubCategory>(); 

var matchingCategories = from mt in categories 
    join sub in subCategories 
     on mt.CategoryId equals sub.CategoryId 
    group sub by new { mt.CategoryId, mt.Name} 
    into grp 
    select new Category() {CategoryId = grp.Key.CategoryId , Name = grp.Key.Name, subCategories = grp.ToList()}; 

var result = matchingCategories.ToList(); 
+0

我想包括类别名称也列入清单。 – sham

+0

@sham,我更新了答案。我希望它可以帮助您 – hiule

+0

@sham,请接受我的答案,并将答案标记为“已接受”。 – hiule