使用group by存储在IEnumerable属性中

时间:2015-03-16 02:17:45

标签: c# linq linq-to-objects

我想创建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 = ??
}

2 个答案:

答案 0 :(得分:0)

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()
}

答案 1 :(得分:0)

您的join声明中存在一些语法问题,您必须在join之前执行group

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()
    }