2017-05-31 176 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