使用 group by 存储在 IEnumerable 属性 中

Store in IEnumerable property by using group by

我想创建 json 对象来表示职位和具有相同职位的用户列表,并将其存储在 JobUsersList 对象

public class JobUsersList
{
    public string JobName { get; set; }
    public IEnumerable<User> Users { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int JobID { get; set; }
}

public class Job
{
    public int Id { get; set; }
    public string JobName { get; set; }
}

我的问题是存储 IEnumerable<User>。不知道是什么问题

from user in userTB
join job in JobTB on userTB.JobID equals job.ID
group people by job into k
select new JobUsersList
{ 
     JobUsersList = k.key, 
     Users = ??
}

group people 更改为 group use 后,这将很容易:kIEnumerable<user>。您可能想对其调用 ToList,以避免多次枚举。

from user in userTB
join job in JobTB on userTB.JobID equals job.ID
group user by job into k
select new JobUsersList
{ 
     JobUsersList = k.key, 
     Users = k.ToList()
}

您的 join 语句中存在一些语法问题,您必须在 group:

之前执行 join
from u in userTB
group u by u.JobID into g
join j in jobTB on g.Key equals j.Id
select new JobUsersList
    {
        JobName = j.JobName,
        Users = g.ToList()
    }