【问题标题】:Anonymous Types in a signature签名中的匿名类型
【发布时间】:2010-09-19 06:46:09
【问题描述】:

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

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

}

【问题讨论】:

    标签: c# asp.net-mvc linq anonymous-types


    【解决方案1】:

    您不应该返回匿名实例。

    您不能返回匿名类型。

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

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

    【讨论】:

      【解决方案2】:

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

      不,你不需要选择!

      【讨论】:

        【解决方案3】:

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

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

        改为创建一个类:

        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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多