Foreach without repeating the name

1

I have a Foreach in View, and it contains Description, qtd and dta, how do I make a foreach without repeating the description? Ex: I have a product X whose 10 units were removed on 10/1/2016, 3 units on 04/10/2016, 8 units on 10/15/2016, how do I display the description only once and the dates and quantities normally?

<style type="text/css">
        .leftDivItem, .rightDivItem {
         border: none;
         float: left;
         width: 29%; /*Aumentar ou diminuir a porcentagem para adicionar ou tirar*/
         overflow: hidden;
         margin-right: 2%;
         margin-left: 2%;
         float: left;
         width: 19%;
         overflow: hidden;
         margin-right: 3%;
         margin-left: 3%;*/
  }
  </style>

   int i = 0;
   foreach (var item in Model)
       {
           if (i % 2 == 0)
           {
               <div class="leftDivItem">
                   <span class="listCol2">
                       <i>@Html.DisplayFor(modelItem => item.Produto.Descricao)</i><br />
                       <i>@Html.DisplayFor(modelItem => item.Produto.Qtd)</i><br />
                       <i>@Html.DisplayFor(modelItem => item.Produto.dta)</i>
                       <br />
                       <br />
                   </span>
               </div>
          }
          else
          {
              <div class="rightDivItem" id="textShadow">
                  <span class="listCol2">
                      <i>@Html.DisplayFor(modelItem => item.Produto.Descricao)</i><br />
                      <i>@Html.DisplayFor(modelItem => item.Produto.Qtd)</i><br />
                      <i>@Html.DisplayFor(modelItem => item.Produto.dta)</i>
                      <br />
                      <br />
                   </span>
              </div>
           }
           i++;
       }

In the code I'm showing, the

<i>@Html.DisplayFor(modelItem => item.Produto.Descricao)</i><br />

And I know that it will repeat itself several times because it is there, but I wanted to know how to position it so that it does not repeat, but only once! Thanks!

    
asked by anonymous 18.10.2016 / 07:07

1 answer

2

One way to solve the problem is by grouping by description. I'm going to use the table element because the example is easier, you may have to make adjustments to your layout:

<table>
@foreach(var grupo in Model.GroupBy(i => i.Produto.Descricao)){
    <tr>
        <td rowSpan="@grupo.Count()"> grupo.Key </td> 
    <tr>
    @foreach(var item in grupo){
       <tr> 
           <td>item.Produto.Descricao</td>
           <td>item.Produto.Qtd</td>
           //...
        <tr>
    }
}
</table>

To sort by quantity simply enter OrderBy into grupo .

grupo.OrderByDescending(i => i.Produto.Qtd)
    
18.10.2016 / 10:07