按内部列表参数分组以过滤外部列表数据

时间:2017-12-06 13:58:49

标签: c# linq lambda

我是编写查询以从对象列表中获取数据的新手。 我有以下类结构


    public class Locations
    {
        public string id { get; set; }
        public string name { get; set; }
        public List model { get; set; }
        public List sectors { get; set; }
    }

    public class Sector
    {
        public string sectoreid { get; set; }
        public string sectorname { get; set; }
        public List streams { get; set; }
        public List employees { get; set; }
    }   

    public class Stream
    {
        public string streamid { get; set; }
        public string streamname { get; set; }
        public string geographyid { get; set; }
        public string geographyname { get; set; }
        public string countryid { get; set; }
        public string countryname { get; set; }
    }

    public class Employee
    {
        public string id { get; set; }
        public string name { get; set; }
        public string code { get; set; }
    }

我正在获取地点列表,我想按列表分组,以便我可以得到结果 我想以这样的方式对这些集合进行分组,以便我可以像Geography一样获得层次结构 - >国家 - >流 - >员工 - >部门 - >位置

还希望它类型转换为特定的类,如


    public class Tree
    {
        public string id { get; set; }
        public string name { get; set; }
        public List nodes{ get; set; }
    }

我在下面尝试了查询


siteList.SelectMany(a => a.streams.Select(b => new { A = a, B = b }).ToList()).ToList()
                         .GroupBy(ol => new { ol.B.geographyid, ol.B.geographyname })
                         .Select(gGroup => new Tree
                         {
                             id = gGroup.Key.geographyid,
                             name = gGroup.Key.geographyname,
                             children = gGroup
                                 .GroupBy(ol => new { ol.B.countryid, ol.B.countryname })
                                 .Select(cGroup => new Tree
                                 {
                                     id = cGroup.Key.countryid,
                                     name = cGroup.Key.countryname,
                                     children = cGroup
                                       .GroupBy(ol => new { ol.B.id, ol.B.name })
                                       .Select(sGroup => new Tree
                                       {
                                           id = sGroup.Key.id,
                                           name = sGroup.Key.name,
                                           children = sGroup
                                            .Select(ol => new Trees { id = ol.A.id, name = ol.A.name, children = new List() })
                                            .ToList()
                                       })
                                      .ToList()
                                 })
                                 .ToList()
                         })
                         .ToList();

0 个答案:

没有答案