views:

410

answers:

3

Hi all,

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>>"

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

}
+3  A: 

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>.

Brad Wilson
+2  A: 

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!

leppie
Ah right, I didnt test it :)
leppie
Actually, you dont need it...
leppie
Nice and simple. +1
David B
+4  A: 

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