2016-11-30 78 views
2

嵌套表我有一個包含以下夾具類的對象的列表:分組與LINQ

public class APIFixtureModel 
{ 
    public string HomeTeamName { get; set; } 
    public string AwayTeamName { get; set; } 
    public string TournamentName { get; set; } 
    public string SportType { get; set; } 
    public DateTime FixtureDateTime { get; set; } 
} 

所以我目前的設置,我得到燈具的列表,這是好的,但我需要一個結構,其中列表按運動類型分組,然後由比賽分組。爲了說明:

public class APIExtendedFixtureModel 
{ 
    private List<Sport> lstSports; 

    class Sport 
    { 
     public string SportType { get; set; } 
     public List<Tournament> lstTournaments; 
    } 

    class Tournament 
    { 
     public string TournamentName { get; set; } 
     public List<Fixture> lstFixtures; 
    } 

    class Fixture 
    { 
     public string HomeTeamName { get; set; } 
     public string AwayTeamName { get; set; } 
     public DateTime FixtureDateTime { get; set; } 
    } 
} 

我曾嘗試以下:

var testgroup = lstFixtures.GroupBy(f => f.SportType, 
            f => f.TournamentName, 
             (key,g) => new 
             { 
              Sport = key, 
              Tournament = g.ToList() 
             }).ToList(); 

我得到的是運動,每個運動節點我得到一個列表比賽中的列表,但是這也正是它停了,我可以似乎沒有對的。

+0

你想輸出什麼? –

+0

APIExtendedFixtureModel類的一個實例。我只是利用這個班級來腐蝕結構 –

回答

2

這返回的Sport列表您可以添加也進一步列本包含錦標賽和賽程的對象:

List<Sport> sports = 
    fixtureList.GroupBy(f => f.SportType).Select(sGroup => new Sport 
     { 
      SportType = sGroup.Key, 
      lstTournaments = sGroup.GroupBy(f => f.TournamentName).Select(tGroup => new Tournament 
       {    
        TournamentName = tGroup.Key, 
        lstFixtures = tGroup.Select(f => new Fixture 
         { 
          HomeTeamName = f.HomeTeamName, 
          AwayTeamName = f.AwayTeamName, 
          FixtureDateTime = f.FixtureDateTime, 
         }).ToList(), 
       }).ToList() 
     }).ToList(); 
-1

如果你想按多列然後創建一個匿名類型:

var testgroup = lstFixtures.GroupBy(f => new { f.SportType, f.TournamentName }, 
             (key,g) => new 
             { 
              Sport = key.SportType, 
              Tournament = key.TournamentName, 
              Result = g.ToList() 
             }); 

如果你想:)