我需要根据IEnumerable<category>
合并categoryId
并列出所有相关的子类别。从Sql我把所有的东西放在一起。
这就是我现在所拥有的:
型号:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
}
结果:
<Category>
<CategoryId>1</CategoryId>
<CategoryName>Shoes</CategoryName>
<SubCategoryId>2</SubCategoryId>
<SubCategoryName>Baby Shoes</SubCategoryName>
</Category>
<Category>
<CategoryId>1</CategoryId>
<CategoryName>Shoes</CategoryName>
<SubCategoryId>4</SubCategoryId>
<SubCategoryName>Man Shoes</SubCategoryName>
</Category>
我需要合并它,并在IEnumberable<category>
位于其中时返回IEnumberable<SubCategory>
:
型号:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public IEnumerable<SubCategory> SubCategory { get; set; }
}
public class SubCategory
{
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
}
结果:
<Category>
<CategoryId>1</CategoryId>
<CategoryName>Shoes</CategoryName>
<SubCategory>
<SubCategoryId>2</SubCategoryId>
<SubCategoryName>Baby Shoes</SubCategoryName>
</SubCategory>
<SubCategory>
<SubCategoryId>2</SubCategoryId>
<SubCategoryName>Baby Shoes</SubCategoryName>
</SubCategory>
</Category>
有可能吗?感谢。
答案 0 :(得分:0)
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Category> lstCategory = new List<Category>()
{
new Category(){CategoryId = 1, CategoryName = "Shoes", SubCategoryId = 2, SubCategoryName = "Baby Shoes"},
new Category(){CategoryId = 1, CategoryName = "Shoes", SubCategoryId = 4, SubCategoryName = "Man Shoes"}
};
var grouped = lstCategory.GroupBy(obj => new { obj.CategoryId, obj.CategoryName}, (key,group)=> new {CategoryId=key.CategoryId,CategoryName=key.CategoryName,SubCategory = group});
}
}
答案 1 :(得分:0)
我命名了你的第一个模型OldCategory
。查询:
var categories = new OldCategory[]
{
new OldCategory {CategoryId = 1, SubCategoryId = 2},
new OldCategory {CategoryId = 1, SubCategoryId = 4}
};
var newCategories = categories
.GroupBy(_ => new
{
Id = _.CategoryId,
Name = _.CategoryName
})
.Select(_ => new Category
{
CategoryId = _.Key.Id,
CategoryName = _.Key.Name,
SubCategories = _.Select(sc => new SubCategory {SubCategoryId = sc.SubCategoryId, SubCategoryName = sc.SubCategoryName})
})
.ToArray();