如何在C#中对LINQ进行多列分组

时间:2019-04-04 10:20:45

标签: linq

我的列表如下:

Health_Plan  HealthMemberType_Name   Health_Benefit_Description     

Silver       Parent                  a1     
Silver       Spouse                  b1     
Silver       Children                c1     
Silver       Parent                  a2         
Silver       Spouse                  b2    
Silver       Children                c2    
Gold         Parent                  a1    
Gold         Spouse                  b1
Gold         Children                c1
Gold         Parent                  a2
Gold         Spouse                  b2
Gold         Children                c2

我希望得到以下结果((按Health_Plan和HealthMemberType_Name分组)

Silver 
   Parent 
       a1     
       a2 
   Spouse 
       b1
       b2

   Children
       c1
       c2

Gold     
   Parent
       a1
       a2

   Spouse            
       b1
       b2

   Children            
       c1
       c2

尝试以下代码:

var _aBenefits = _lHealthBenefit.GroupBy(o1 => new { o1.Health_Plan_Pid, o1.Health_Plan }).Select(grp1 => new Health_Benefits_Consolidated
                                    {
                                        Health_Plan_Pid = grp1.Key.Health_Plan_Pid,
                                        Health_Plan = grp1.Key.Health_Plan,
                                        Health_Benefits = grp1.ToList()
                                    }).ToList();

     public class Health_Benefits
    {
        public long Health_Plan_Pid { get; set; }
        public string Health_Plan { get; set; }
        public string Health_Benefit_Description { get; set; }
        public double Health_MaxLimit { get; set; }
        public string HealthMemberType_Name { get; set; }
        public string CCY { get; set; }
        public int Max_Member { get; set; }
    }

    public class Health_Benefits_Consolidated
    {
        public long Health_Plan_Pid { get; set; }
        public string Health_Plan { get; set; }
        public int Max_Member { get; set; }
        public List<Health_Benefits> Health_Benefits { get; set; }
    }

看起来我必须将“ HealthMemberType_Name”分组到列表中。.但是我不知道如何将组插入“ Health_Benefits = grp1.ToList()”

任何帮助表示赞赏。

非常感谢

问候 唐

1 个答案:

答案 0 :(得分:0)

因此,您想将输入项目分组为具有相同HealthPlan的输入项目组。

每个组的元素必须分组为子组,其中子组的每个元素都具有HealthMemberTypeName

每个子组的元素是此HealthBenefitDescriptions的{​​{1}}

为此,我们在另一个GroupBy中使用一个GroupBy。我们使用Enumerable.GroupBy overload that has a resultSelector

Group - SubGroup

长标识符名称可能会使您难以阅读,但与使用x,y,z相比,我认为它可以帮助您更好地理解其中的含义。复数是序列,单数是这些序列的元素