Iterate over sublists within a list

1

I currently have a list of the Activity class, this class, among other properties, has one that is Operational.

The fact is that I take charge of all the activities of all the workers in the lAux list and what I need is from that great list to be able to deal with all the activities of each operator, for this I try to do the following :

As you can see it gives compilation error.

I would need to be able to treat all sublists generated with each different Operator within the foreach, or some similar treatment. Thanks for the help.

Edit: I put the code with the modification of Einer, it works fine, the only thing if it can be optimized.

    
asked by U. Busto 22.11.2017 в 13:04
source

2 answers

2

IdOperario is of type int and when you do Select(x=>x.IdOperario) you are creating a list of int , not of Actividad so it tells you that you can not convert a type int to List<Actividad> .

So change:

foreach(List<Actividad> lista in lUx.Select(x=>X.IdOperario).Distinct().ToList())
{

}

By:

foreach(int idOperatorio in lUx.Select(x=>X.IdOperario).Distinct().ToList())
{

}

Update:

As you mention that you need to group by activity and that same class that has the data you need, you can use GroupBy(x=>X.IdOperario) where the list grouped by IdOperario will give you:

foreach( IEnumerable<IGrouping<int, List<Actividad>> actividadesAgrupadas in lUx.GroupBy(x=>X.IdOperario))
{
    foreach(Actividad actividad in actividadesAgrupadas)
    {
        // actividad agrupada por el operario
        Console.WriteLine(actividad.InicioTrabajo);
    }
}
    
answered by 22.11.2017 / 13:09
source
4

Even though @Einer's response is totally correct, you're probably looking for a GroupBy more than a Select . If what you want is to see all the activities of each Operator, the most logical thing is to group them by the Operative Id to later go through in a loop each activity of said operator. I would do something like this:

foreach (var agrupado in lUx.GroupBy(x => x.IdOperario))
{
    //en agrupado.Key tienes el IdOperario
    foreach(var actividad in agrupado)
    {
        //en actividad vas recorriendo cada actividad del operario
        //podrias acceder a actividad.InicioTrabajo, actividad.Duracion, actividad.IdOperario...
        //
    }
}

Or, if what you need is a list of each operator to process it, simply:

foreach (var agrupado in lUx.GroupBy(x => x.IdOperario))
{
    List<Actividad> lista = agrupado.ToList();
    int? secs = lista.Sum(x=>x.Duracion);
    GestionExcel.generaInformeIndividual(lista, secs);  
}
    
answered by 22.11.2017 в 13:24