将平面列表转换为对象

时间:2013-11-28 08:12:33

标签: c#

我正在尝试将平面结构转换为层次结构。

列表如下所示,其中personid,first和lastname出现多次:

public class VisitType
{
    public Guid Id { get; set; }
    public Guid PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string VisitName { get; set; }

    public DateTime TimeFrom { get; set; }
    public DateTime TimeTo { get; set; }

}

我希望将其转换为这样,而客户端只发生一次,每次访问都归为:

public class Client {

    public String FirstName { get; set; }
    public string LastName { get; set; }
    public Guid PersonId { 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; }

}

最快的方法是什么?

2 个答案:

答案 0 :(得分:2)

在LinqPad中试试

var list = new []{
    new { PersonId = 1, Name = "Is", Lastname = "Shin", VisitName = "a" },
    new { PersonId = 1, Name = "Is", Lastname = "Shin", VisitName = "b" },
};

(
from i in list
group i by i.PersonId into g
let first = g.First()
select new {
    Person = new { ID = first.PersonId, Name = first.Name, Lastname = first.Lastname },
    Visits = g.Select(gi => new { VisitName = gi.VisitName } )
}
).Dump();

答案 1 :(得分:1)

为了完整起见,使用method syntax的相同查询,我个人更喜欢:

var result = visitLists.GroupBy(vt => vt.PersonId, (g, e) => 
    new
    {
        First = e.First(),
        List = e
    }).Select(i =>
    new Client()
    {
        FirstName = i.First.FirstName,
        LastName = i.First.LastName,
        PersonId = i.First.PersonId,
        Visits = i.List.Select(vt => new Visit()
                {
                    Name = vt.VisitName,
                    StartAfter =  vt.TimeFrom,
                    StartBefore = vt.TimeTo
                }).ToArray()
    }).ToList();