Domanda

Sto cercando di far funzionare la firma sul metodo seguente. Dato che si tratta di un tipo anonimo, ho qualche problema, qualsiasi aiuto sarebbe ottimo.

Quando ho guardato sortGameList.ToList () in una finestra di QuickWatch ho ricevuto la firma

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

Molte grazie

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

}
È stato utile?

Soluzione

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

Modifica: è sbagliato! Penso che lo farà.

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

    return sortedGameList.ToList();
}

E no, non è necessario selezionare!

Altri suggerimenti

Non dovresti restituire istanze anonime.

Non puoi restituire tipi anonimi.

Crea un tipo (chiamato) e restituiscilo:

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

La semplice risposta è: non usare un tipo anonimo.

Il più vicino che otterrai con quel tipo anonimo è IEnumerable < object > ;. Il problema è che chiunque usi le tue cose non saprà cosa fare con quell'oggetto il cui tipo era & Quot; imprevedibile & Quot ;.

Invece, crea una classe come:

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

E cambia il tuo LINQ in:

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

Ora stai tornando alla Lista < GamesWithDate > ;.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top