将多个记录分组到一个记录中

时间:2017-09-04 09:47:59

标签: c# .net linq linq-to-entities

我有两个班级 -

public class MyUser
{
    public string UserID{ get; set; }
    public string UserFirstName{ get; set; }
    public string UserLastName{ get; set; }
    public string UserEmail{ get; set; }
    public string RoleId{ get; set; }
    public string RoleName { get; set; }
    public string GroupId{ get; set; }
    public string GroupName{ get; set; }
}

public class FinalUsers
{
    public string UserID{ get; set; }
    public string UserFirstName{ get; set; }
    public string UserLastName{ get; set; }
    public string UserEmail{ get; set; }
    public List<string> RoleId{ get; set; }
    public List<string> RoleName { get; set; }
    public List<string> GroupId{ get; set; }
    public List<string> GroupName{ get; set; }
}

我在MyUser中获取记录为.net list -

 |UserId | UserFirstName | UserLastName | UserEmail  | UserRoleId | UserRoleName | UserGroupId | UserGroupName
 | 1     | Anil          | Surname1     | abc@ab.com | R123       | Read         | NULL        | NULL
 | 1     | Anil          | Surname1     | abc@ab.com | R234       | Write        | NULL        | NULL
 | 1     | Anil          | Surname1     | abc@ab.com | null       | null         | G1          | Group1
 | 1     | Anil          | Surname1     | abc@ab.com | null       | null         | G2          | Group2

现在我想将其转换为FinalUsers

 |UserId | UserFirstName | UserLastName | UserEmail  | UserRoleId | UserRoleName | UserGroupId | UserGroupName
 | 1     | Anil          | Surname1     | abc@ab.com | R123,R234  | Read,Write   | G1,G2       | Group1,Group2

不确定如何在linq中对其进行分组 -

from p in myUserList
   group p by new
   {
       p.RoleId,
       p.RoleName,
       p.GroupId,
       p.GroupName,
   } into gcs
   select new FinalUsers()
   {
       UserId = gcs.FirstOrDefault().UserId,
       UserFirstName = gcs.FirstOrDefault().UserFirstName ,
       UserLastName = gcs.FirstOrDefault().UserLastName ,
       UserEmail = gcs.FirstOrDefault().UserEmail ,
       RoleId = gcs.RoleId,
       RoleName = gcs.RoleName,
       GroupId= gcs.GroupId,
       GroupName= gcs.GroupName
   }

我确定上述查询不正确,请您帮我纠正一下。或者建议另一种方法来实现结果。

1 个答案:

答案 0 :(得分:2)

我认为问题出在您的group by声明中:

   from p in myUserList
   group p by p.UserId into gcs
   select new FinalUsers()
   {
       UserId = gcs.Key,
       UserFirstName = gcs.Select(g => g.UserFirstName).First() ,
       UserLastName = gcs.Select(g => g.UserLastName ).First(),
       UserEmail = gcs.Select(g => g.UserEmail).First() ,
       RoleId = gcs.Select(g => g.RoleId).ToList(),
       RoleName = gcs.Select(g => g.RoleName).ToList(),
       GroupId= gcs.Select(g => g.GroupId).ToList(),
       GroupName= gcs.Select(g => g.GroupName).ToList()
   }

值得一提的是,您的类的结构具有冗余信息,例如:用户的姓名,用户的电子邮件,组名和角色名称,您最好为用户的信息,组的信息制作不同的类,和角色信息。