Linq group by但返回所有属性

时间:2013-11-27 08:57:47

标签: c# linq list

我有一个列表,其中的对象看起来像这样。

  public class Resource
{
    public Guid Id { get; set; }
    public Guid PersonId { get; set; }
    public string PersonFirstName { get; set; }
    public string PersonLastName { get; set; }


    public string VisitName { get; set; }


    public VisitPlan[] Visits { get; set; }

}

public class VisitPlan
{
    public DateTime StartAfter { get; set; }
    public DateTime StartBefore { get; set; }
    public Competence[] Skills { get; set; }
}


public class Competence {

    public Guid Code { get; set; }
    public string Name { get; set; }  
}

目前,该列表包含多个具有相同ClientSSN,FirstName和LastName的项目。

我想将它们分组,以使它看起来更像这样,并且没有重复的客户信息。

public class Client {

    public String FirstName { get; set; }
    public string LastName { get; set; }
    public Guid ClientId { get; set; }
    public Visit[] Visits { get; set; }
}


public class Visit {

    public string Name { get; set; }
    public DateTime StartBefore { get; set; }
    public DateTime StartAfter { get; set; }


}

我根据SSN和访问分组了一个简单的组,但后来我才能访问SSN和访问。

                var results = from v in visits
                          group v.Visits by v.PersonId into g
                          select new { 
                              PersonID = g.Key, 
                              Visits = g.ToList(),

                          };

另一种可能性是使用临时列表,但我无法理解我的想法。

1 个答案:

答案 0 :(得分:0)

from r in Resources
group r by new { 
   r.PersonId, 
   r.PersonFirstName,
   r.PersonLastName
} into g
select new Client {
    ClientId = g.Key.PersonId,
    FirstName = g.Key.PersonFirstName,
    LastName = g.Key.PersonLastName,
    Visits = g.SelectMany(r => r.Visits).ToArray()
}

注意:因此,您有两个名称完全相同的Visit类,最后我选择了来自组的所有访问,而不是创建一些Visit属性的Name个实例。

更新:如果您的第一个访问类名为VisitPlan,则完整查询如下:

from r in Resources
group r by new { 
   r.PersonId, 
   r.PersonFirstName,
   r.PersonLastName
} into g
select new Client {
    ClientId = g.Key.PersonId,
    FirstName = g.Key.PersonFirstName,
    LastName = g.Key.PersonLastName,
    Visits = g.SelectMany(r => 
                 r.Visits.Select(v => new Visit {
                     Name = r.VisitName,
                     StartBefore = v.StartBefore,
                     StartAfter = v.StartAfter
                 })).ToArray();

}