我从域中获取域相关信息作为简单列表,现在我需要在绑定到视图之前对信息进行分组。这是我的课程详情。我尝试了各种组逻辑,但无法实现结果
public class CapabilitySelectionModel
{
public string Domain { get; set; }
public string Category { get; set; }
public string Capability { get; set; }
}
List<CapabilitySelectionModel> list1 = new List<CapabilitySelectionModel>();
list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability1" });
list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category1", Capability = "Capability2" });
list1.Add(new CapabilitySelectionModel { Domain = "Domain1", Category = "Category2", Capability = "Capability1" });
list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category1", Capability = "Capability1" });
list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability1" });
list1.Add(new CapabilitySelectionModel { Domain = "Domain2", Category = "Category2", Capability = "Capability2" });
它看起来像这样
Domain1
Category1
Capability1
Capability2
Category2
Capability1
Domain2
Category1
Capability1
Category2
Capability1
Capability2
现在,我想将此列表转换为以下列表格式
public class DomainModel
{
public string DomainName { get; set; }
public List<CategoryModel> CategoryModel { get; set; }
}
public class CategoryModel
{
public string CategoryName { get; set; }
public List<CapablityModel> CapablityModel { get; set;}
}
public class CapablityModel
{
public string CapablityName { get; set; }
}
有人可以提供建议吗?
答案 0 :(得分:1)
未经测试,但您只需要一些嵌套分组:
var results = list1
.GroupBy(a => a.Domain)
.Select(g => new DomainModel {
DomainName = g.Key,
CategoryModel = g.GroubY(b => b.Category)
.Select(h => new CategoryModel {
CategoryName = h.Key,
CapablityModel = h.Select( c => new CapablityModel {
c.CapablityName }).ToList()
}).ToList()
}).ToList();