时间:2019-03-08 标签:c#list

c# list Group By

我正在从数据库中获取作为简单列表的域相关信息,现在我需要在绑定到视图之前对信息进行分组。这是我的 Class 详细信息。我尝试了各种组逻辑,但无法获得结果

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; }
    }

有人可以建议吗?

未测试,但您只需要一些嵌套分组:

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();