Performing Groupby with Linq?

Asked

Viewed 35 times

1

I’m trying to perform a Groupby but I’m not getting it. Always returns an Exception that I’m not able to solve.

How do I solve this problem ?

LINQ

public ActionResult MeusConcursos(){
            Usuario _usuario = Session["Usuario"] as Usuario;   

            //agrupa concurso         
            var query = context.numerosSorteio.GroupBy(n => n.concurso.id).OrderBy(n => n.Key); 
            //casting para lista
            IList<NumeroSorteio> numeros = (List<NumeroSorteio>)query;
            //define valores para o model
            IList<MeusConcursosModel> _lista = numeros.Where(x => x.usuario.id == _usuario.id)
                                                                       .Select(x => new MeusConcursosModel
                                                                       {
                                                                           id = x.concurso.id,
                                                                           dataRealizado = x.concurso.dataFinalizado,
                                                                           premio = x.concurso.premio.nome,
                                                                           valorUnit = x.valor,
                                                                           statusDesc = x.concurso.status
                                                                       })
                                                                       .OrderByDescending(x => x.id)
                                                                       .ToList();


            return View(_lista);
        }

Exception

An exception of type 'System.InvalidCastException' occurred in PremiosOn.dll but was not handled in user code

Additional information: Não é possível converter um objeto do tipo 'System.Data.Entity.Infrastructure.DbQuery`1[System.Linq.IGrouping`2[System.Int64,NumeroSorteio]]' no tipo 'System.Collections.Generic.List`1[NumeroSorteio]'.
  • it seems the result of your group is a Int64and not a List<NumeroSorteio>

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.