Simulate a Master/Detail report with foreach

Asked

Viewed 66 times

3

I have a table as follows:

public class Producao
{
    string unidade;
    string profissional;
    string procedimento;
}

I can take all the records stored in the table and play them on a list listaProducao. And list them through a foreach as follows:

<table>
<tr>
    <td>Unidade</td>
    <td>Profissional</td>
    <td>Procedimento</td>
</tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.unidade</td>
            <td>@item.profissional</td>
            <td>@item.procedimento</td>
        </tr>
    }
</table>

The result is similar to the one shown below:

unidade - profissional - procedimento
   1           1              1
   1           2              1
   1           2              2
   1           3              1
   1           3              3

What I want is to generate a result like this:

UNIDADE 1
--------------------
PROFISSIONAL 1
--------------------
procedimento 1
--------------------
PROFISSIONAL 2
--------------------
procedimento 1
procedimento 2
--------------------
PROFISSIONAL 3
--------------------
procedimento 1
procedimento 3

Note that the result is similar to a Master/Detail report, where you first list the unit, all its professionals and their procedures. Then list another unit if you have it in the table.

Any tips on how to do it?

1 answer

3


Following this output you requested, you can do so:

<table>
    @foreach (var unidade in Model.GroupBy(i => i.unidade))
    {
        <tr>
            <td>UNIDADE @unidade.Key</td>
        </tr>
        foreach (var profissional in unidade.GroupBy(i => i.profissional))
        {
            <tr>
                <td>PROFISSIONAL @profissional.Key</td>
            </tr>
            foreach (var p in profissional)
            {
                <tr>
                    <td>Procedimento @p.procedimento</td>
                </tr>
            }
        }
    }
</table>
  • Alisson, this example worked normally on MVC, but I tried to use it now on Windowsforms and it’s not working. Can you make an example in Windowsforms too? Hug.

  • 1

    @Italorodrigo how are you trying to display the results? Including in some DataGrid? Which part is not working?

  • If I do so in the first line: foreach (Producao unidade in listaProducao.GroupBy(i => i.unidade)) it gives error in the second line foreach (var profissional in unidade.GroupBy(i => i.profissional)) says that unidade doesn’t have a Getenumerator

  • Alisson, I got it. Thanks anyway

  • 1

    @Italorodrigo try to use foreach (var unidade in listaProducao (utilize var instead of Producao).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.