How to Group Attribute in a class with C #


I would like you to help me I have 3 instances of a class that have the attributes period, soles_vac, dollars_vac, expenses

by which in each instance I have in the same period different amounts in different attributes I would like you to only get now that per period already get the attributes as well as the image

I did it with linq through a groupby but I did not get what it required.

public static list<Flujo>Crear(List<Flujo> ListaFlujo)
return ListaFlujo.GroupBy(f =>f.periodo).Select(f =>new FlujoSP
periodo = f.FirstOrDefault().Periodo,
Soles_vac =f.FirstOrDefault().Soles_vac ,
Dolares_vac  =f.FirstOrDefault().Dolares_vac   ,
gastos = f.FirstOrDefault().gastos

asked by PieroDev 02.01.2019 в 19:37

1 answer


I propose that after the grouping you validate item by item the values you want to obtain.

public static List<Flujo> Crear(List<Flujo> ListaFlujo)
    List<Flujo> listaFlujoFinal = new List<Flujo>();

    Flujo flujoNuevo;
    Flujo flujoTemp;

    List<IGrouping<int, Flujo>> listaFlujoAgrupado = ListaFlujo.GroupBy(f => f.Periodo).ToList();

    foreach (IGrouping<int, Flujo> periodoAgrupado in listaFlujoAgrupado)
        flujoNuevo = new Flujo();

        flujoNuevo.Periodo = periodoAgrupado.Key;

        // buscando la primera coincidencia donde Soles_vac contenga valor.
        flujoTemp = periodoAgrupado.FirstOrDefault(c => c.Soles_vac != 0);

        if (flujoTemp != null) flujoNuevo.Soles_vac = flujoTemp.Soles_vac;

        // buscando la primera coincidencia donde Dolares_vac contenga valor.
        flujoTemp = periodoAgrupado.FirstOrDefault(c => c.Dolares_vac != 0);

        if (flujoTemp != null) flujoNuevo.Dolares_vac = flujoTemp.Dolares_vac;


    return listaFlujoFinal;

Within the foreach you can add more validation rules, for example if you only find a period or if there are more periods.

In the code fragment that I'm leaving I'm assuming that Periodo is an integer and that Soles_vac and Dolares_vac are decimals.

answered by 02.01.2019 в 20:39