Get next record in a clustered foreach

1

How could I be selecting the next record within a grouped foreach before it ends, without advancing in that loop ?

The point where I think I might be getting this information is where GET THE NEXT ID DESSE FOREACH is written in the code below:

decimal? valor = 0;
@foreach (var item in Model.Lista.GroupBy(d => d.Nome)
                              .Select(
                               g => new
                               {
                                 key = g.Key,
                                 Id = g.First().Id,
                                 NomeFantasia = g.First().NomeFantasia,
                                 ValorTotal = g.Sum(s => s.ValorTotal) }))
{
   <tr>
     <td>Id</td>
     <td>Nome</td>
     <td>Valor</td>
   </tr>

   valor += item.Valor;

   <!- **OBTER O PRÓXIMO ID DESSE FOREACH** -->

}

   <tr>
     <td colspan="2"></td>
     <td>@Valor</td>
   </tr>
    
asked by anonymous 09.08.2018 / 16:24

2 answers

1

You can not use for each when you want to control the index, so there is for :

var valor = 0M;
@foreach (var i = 0; i < model.Count(); i++) {
    <tr>
        <td>Id</td>
        <td>Nome</td>
        <td>Valor</td>
    </tr>
    valor += model[i].Valor;
    var proximoID = model[i + 1].Id;
}

I placed GitHub for future reference a>.

    
09.08.2018 / 18:11
0

You can use a counter to be the index of iterations and use the i+1 value to access your list.

@{int i = 0;}
@foreach(...)
{
    <span>@i+1</span>

    i++;
}

Edit:

var lista = Model.Lista.GroupBy(d => d.Nome)
                          .Select(
                           g => new
                           {
                             key = g.Key,
                             Id = g.First().Id,
                             NomeFantasia = g.First().NomeFantasia,
                             ValorTotal = g.Sum(s => s.ValorTotal) });

@{decimal? valor = 0;int i = 0;}
@foreach (var item in )
{
   <tr>
     <td>Id</td>
     <td>Nome</td>
     <td>Valor</td>
   </tr>

   valor += item.Valor;

   <!- **OBTER O PRÓXIMO ID DESSE FOREACH** -->
   lista[i++].Id
}
    
09.08.2018 / 16:55