2008-10-26 78 views
4

我正試圖在下面的方法上使用簽名。由於這是一個匿名類型,我有一些麻煩,任何幫助將是偉大的。簽名中的匿名類型

當我在一個快速監視窗口看着sortedGameList.ToList()我得到的簽名

System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>> 

非常感謝

唐納德

public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) 
{ 
    var sortedGameList = 
     from g in Games 
     group g by g.Date into s 
     select new { Date = s.Key, Games = s }; 

    return sortedGameList.ToList(); 

} 

回答

6

select new {Date = s.Key,Games = s.ToList()};

編輯:多數民衆贊成在錯!我認爲這會做。

public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) 
{ 
    var sortedGameList = 
     from g in Games 
     group g by g.Date; 

    return sortedGameList.ToList(); 
} 

不,你不需要選擇!

+0

啊對,我沒有實際測試吧:) – leppie 2008-10-26 15:13:54

4

簡單的答案是:不使用匿名類型。

您最近得到的匿名類型是IEnumerable < object>。問題是,任何使用你的東西的人都不知道該如何處理類型爲「不可預知」的對象。

相反,使類,如:

public class GamesWithDate { 
    public DateTime Date { get; set; } 
    public List<Game> Games { get; set; } 
} 

,改變你的LINQ to:

var sortedGameList = 
    from g in Games 
    group g by g.Date into s 
    select new GamesWithDate { Date = s.Key, Games = s }; 

現在你返回列表< GamesWithDate>。

6

您不應該返回匿名實例。

您不能返回匿名類型。

做一個類型(命名),並返回:

public class GameGroup 
{ 
    public DateTime TheDate {get;set;} 
    public List<Game> TheGames {get;set;} 
} 

//

public List<GameGroup> getGamesGroups(int leagueID) 
{ 
    List<GameGroup> sortedGameList = 
    Games 
    .GroupBy(game => game.Date) 
    .OrderBy(g => g.Key) 
    .Select(g => new GameGroup(){TheDate = g.Key, TheGames = g.ToList()}) 
    .ToList(); 

    return sortedGameList; 
}