在C#列表中进行行分组

时间:2014-02-25 12:38:47

标签: c# c#-4.0

我有以下课程

public  class test
{
    public long missionId { get; set; }  
    public string[] missionAcrynom { get; set; }
    public  Guid userId { get; set; }
    public string userName { get; set; }
    public string email { get; set; }
}

以及以下代码。

using (var ctx = new dbContext())
{
    var userList = (from u in ctx.aspnet_Users select new {u.UserId, u.UserName}).ToList();

    List<test> lst = new List<test>();
    foreach (var user in userList)
    {
        var UserMissionList = (from m in ctx.UserMission from rpt in ctx.Report
                               where m.UserId == user.UserId
                       select new
                       {
                           m.MissionId,
                           m.Mission.Acronym,
                           m.UserId,
                           m.aspnet_Membership.aspnet_Users.UserName,
                           m.aspnet_Membership.Email
                       }).Distinct().ToList();

        foreach (var mission in UserMissionList)
        {
            lst.Add(new test
            {
                    userId = mission.UserId,                            
                    missionId = mission.MissionId,
                    missionAcrynom = new[] {mission.Acronym},
                    userName = mission.UserName,
                    email = mission.Email
            });
        }
    }
}

我想要的是按userId对我的List<test> lst列表中的值进行分组,但仍然存储每个唯一userId行的missionAcrynom字符串数组中所有已过滤行的所有mission.Acronym值。

1 个答案:

答案 0 :(得分:0)

因此,您希望将所有missionAcrynom展平为每个用户组的更大数组?

您可以使用group.SelectMany(...).ToArray()

List<test> groups = lst
    .GroupBy(t => new { t.userId, t.userName, t.email })
    .Select(g => new test
           {  
               userId = g.Key.userId,                            
               missionId = g.First().missionId, // take the first arbitrarily
               missionAcrynom = g.SelectMany(t => t.missionAcrynom).ToArray(),
               userName = g.Key.userName,    
               email = g.Key.email 
           })
    .ToList();