我试图让下面的方法上的签名工作。由于这是一个匿名类型我有一些麻烦,任何帮助都会很棒。

当我在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();

}
有帮助吗?

解决方案

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

不,你不需要选择!

其他提示

您不应该返回匿名实例。

您无法返回匿名类型。

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

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;
}

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

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

相反,请创建一个类:

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 <!> lt; GamesWithDate <!> gt;。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top