将列表值添加到LINQ查询

时间:2014-12-26 20:44:09

标签: c# linq

我有以下要使用的对象(视图模型):

public class assignmentViewModel 
{
    public string choreName { get; set; }
    public List<string> personName { get; set; }

}

LINQ声明:

            var avm = (from a in Assignments
                       join c in Chores on a.ChoreID equals c.ChoreId
                       join p in Persons on a.PersonID equals p.PersonID
                       select new assignmentViewModel
                       {
                           personName = p.PersonName.ToList(),
                           choreName = c.ChoreName
                       }).ToList();

我可以在作业中有多个人。我希望能够将我的数据撤回到此ViewModel中。我目前得到的错误是:

  

无法隐式转换类型&#39; System.Collections.Generic.List<char>&#39;   到&#39; System.Collections.Generic.List<string>&#39;

我的数据(如果有帮助)是:

chore #1
person 1

chore #2
person 1 
person 2

Person模型是:

public partial class person
{
    public int personID { get; set; }
    public string personName { get; set; }
    public System.DateTime personDOB { get; set; }
    public string personEmail { get; set; }
    public string personPhone { get; set; }
    public string personPhoneCarrier { get; set; }
    public bool isActive { get; set; }
}

1 个答案:

答案 0 :(得分:2)

您正在寻找分组,您需要根据choreName对记录进行分组,我会这样做:

(from a in Assignments
 join c in Chores on a.ChoreID equals c.ChoreId
 join p in Persons on a.PersonID equals p.PersonID
 select new 
        {
            person = p,
            choreName = c.ChoreName
        })
  .GroupBy(x => x.choreName)
  .Select(g => new assignmentViewModel
               {
                   personName = g.Select(x => x.person.PersonName).ToList()
                   choreName =  g.Key
               }).ToList();