2008-10-26 59 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; 
}