Flat to collection to One to Many系列

时间:2016-03-15 10:02:59

标签: c# linq

我需要获取由于具有连接等的查询而创建的对象列表,并生成一对多的对象层次结构。我如何使用Linq做到这一点?

class Source
{
  int Id,
  string Name,
  ....  
  int MemberId,
  string MemberName,
  ....
}

class Target
{
  int Id,
  string Name,
  ....
  ICollection<Member> Members
}

class Member
{
  int Id,
  string Name,
  ....
}

示例数据

List = 
{
  new Source {Id = 1, Name = "Test1", ... MemberId = 1, MemberName = "John", ...},
  new Source {Id = 2, Name = "Test2", ... MemberId = 2, MemberName = "Max", ...},
  new Source {Id = 2, Name = "Test2", ... MemberId = 4, MemberName = "Ruby", ...}
}

期望的结果

List = 
{
  new Target {Id = 1, Name = "Test1", ... 
              Members = new List { new Member {Id = 1, Name = "John", ...}}
             },
  new Target {Id = 2, Name = "Test2", ... 
              Members = new List { new Member {Id = 2, Name = "Max", ...},
                                   new Member {Id = 4, Name = "Ruby", ...}}
             }
}

1 个答案:

答案 0 :(得分:0)

您正在寻找Enumerable.GroupBy,您必须按匿名类型进行分组:

var result = List
    .GroupBy(s => new { s.Id, s.Name })
    .Select(xGrp => new Target
    {
        Id = xGrp.Key.Id,
        Name = xGrp.Key.Name,
        Members = xGrp
            .Select(s => new Member 
            { 
                Id = s.MemberId, 
                Name = s.MemberName
            })
            .ToList()
    })
    .ToList();