Linq,如何按ID对数据进行分组并合并该ID中的数据

时间:2016-11-11 16:53:31

标签: c# linq

从数据库中我得到以下值

PlanningID = GetValue<int>(dataReader["PlanningID"]),
PlanningStatus = GetValue<string>(dataReader["PlanningStatus"]),
Private = GetValue<int>(dataReader["Private"])
Social = GetValue<int>(dataReader["Social"])

PlanningID,PlanningStatus,Private

  • 1,好,10
  • 1,fair,5
  • 1,不好,1

我希望按planningID对这些内容进行分组,以便它看起来像这样

public class ClassResult
{
   public int planningID { get; set; }
   public List<PlanningStatus> PlanningStatus { get; set; }
}

public class PlanningStatus
{
   public string PlanningStatus { get; set; }
   public int Private { get; set; }
   public int Social{ get; set; }
}

我试过这个,但输出错了:

IEnumerable<ClassResult> classResult =
                from result in results
                group result by new
                {
                    result.PlanningID,
                    result.PlanningStatus
                } into grouping

                select new ClassResult
                {
                    PlanningID = grouping.Key.PlanningID,
                    PlanningStatus = grouping.Key.PlanningStatus,                    
                    Private = grouping.First().Private,
                    Social = grouping.First().Social
                };

return lrrResults;

说实话,我不知道该怎么做

根据以下建议更新了投影,但仍有多个计划ID,例如1

            var results =
            from result in results
            group result by result.PlanningID
            into grouping
            select new ClassResult
            {
                PlanningID = grouping.Key,                     
                PlanningStatusType = grouping.Select(item => new PlanningStatusType
                {
                    PlanningStatus = item.PlanningStatus,
                    Private = item.Private,
                    Social = item.Social,
                }).ToList(),
                LatestChange = grouping.First().LatestChange,
                WeeklyChangeType = grouping.First().WeeklyChangeType,
                Address = grouping.First().Address
            };

1 个答案:

答案 0 :(得分:2)

在上面的查询中,您按PlanningIDPlanningStatus分组,因此这些组每个都包含1个项目。你想要做的是:

  1. 像您一样实例化新的ClassResult,但设置planningID但设置.Key(现在只是一个属性
  2. 使用PlanningStatus
  3. 将分组的每个项目投影到.Select()类型的新对象

    代码:

    var classResult = from result in results
                      group result by result.PlanningID into grouping
                      select new ClassResult
                      {
                          PlanningID = grouping.Key,
                          PlanningStatus = grouping.Select(item => new PlanningStatus {
                              PlanningStatus = item.PlanningStatus,
                              Private = item.Private,
                              Social = item.Social
                          }).ToList()
                      };
    

    测试了一些示例代码并运行: enter image description here