2016-03-15 123 views
0

我需要獲取作爲查詢與連接等結果創建的對象的列表,併產生一對多的對象層次結構。我如何與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", ...}} 
      } 
} 

回答

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(); 
+0

非常感謝,這是我正在尋找的 – Matt