How to get all the fields after groupby in LINQ

297 Views Asked by At

I have this object

result view

result view desglosed

With Fecha="Julio2017" I have 2 items and I need to group these three items by SubcontratistaId and Fecha.

item1.Realizado=4060.000 and item2.Realizado=-4060.000 So I need to show in Julio2017 the value of 0

So I try this

private IEnumerable<SubcontratacionesEnFecha> GetRealizadosEnFecha(string proyectoId)
.....   
return realizadosAbonadosEnFechaAcumulados
   .GroupBy(x => new { x.SubcontratistaId, x.Fecha })

But now I don't know how to get the values of all the items grouped

If I try this I get error error

If I try this

return realizadosAbonadosEnFechaAcumulados
   .GroupBy(x => new { x.SubcontratistaId, x.Fecha })
   .Select(x=>x.First())
   .ToList();

I get this

no agrupado con first

That is, I get the first value of the items grouped

Any idea Please?

Thanks

2

There are 2 best solutions below

1
On

I Found this way

var agrupacion = from p in realizadosAbonadosEnFechaAcumulados
                   group p by new { p.SubcontratistaId, p.Fecha } into grupo
                   select grupo;

        foreach (var grupo in agrupacion)
        {
            foreach (var objetoAgrupado in grupo)
            {
              resultAgrupado.Add(new SubcontratacionesEnFecha
               {
                SubcontratistaId = objetoAgrupado.SubcontratistaId,
                NombreSubcontratista= objetoAgrupado.NombreSubcontratista,
                ProyectoId = objetoAgrupado.ProyectoId,
                Fecha = objetoAgrupado.Fecha,
                Mes = objetoAgrupado.Mes,
                Año = objetoAgrupado.Año,
                Realizado = objetoAgrupado.Realizado,
                Planificado = objetoAgrupado.Planificado
              });

             }
           } 

  return resultAgrupado;      
0
On

GroupBy returns IGrouping<,>, which has Key and itself is IEnumerable<> of grouped items. So more probable usage is:

return realizadosAbonadosEnFechaAcumulados
   .GroupBy(x => new { x.SubcontratistaId, x.Fecha })
   .Select(g => new 
   { 
      g.Key.SubcontratistaId,
      g.Key.Fecha,
      Items = g.ToList()
   })
   .ToList();