5

我正在尝试使以下方法的签名生效。由于这是匿名类型,我遇到了一些麻烦,任何帮助都会很棒。

当我在 QuickWatch 窗口中查看 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();

}
4

3 回答 3

7

您不应该返回匿名实例。

您不能返回匿名类型。

创建一个类型(命名)并返回:

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;
}
于 2008-10-26T15:07:54.283 回答
6

选择新的 { 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();
}

不,您不需要选择!

于 2008-10-26T15:06:58.217 回答
5

简单的答案是:不要使用匿名类型。

与该匿名类型最接近的是 IEnumerable<object>。问题是,任何使用你的东西的人都不知道如何处理类型“不可预测”的对象。

相反,制作一个像这样的类:

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

并将您的 LINQ 更改为:

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

现在您返回 List<GamesWithDate>。

于 2008-10-26T15:03:49.953 回答