Question

I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.

When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature

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

Many Thanks

Donald

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

}
Was it helpful?

Solution

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

Edit: thats wrong! I think this will do.

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

    return sortedGameList.ToList();
}

And no, you do not need the select!

OTHER TIPS

You shouldn't return anonymous instances.

You can't return anonymous types.

Make a type (named) and return that:

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

The simple answer is: don't use an anonymous type.

The closest you're going get with that anonymous type is IEnumerable<object>. The problem is, anybody who uses your stuff is not going to know what to do with that object whose type was "unpredictable".

Instead, make a class like:

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

And change your LINQ to:

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

Now you're returning List<GamesWithDate>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top