James Wilson
James Wilson

Reputation: 5150

How to group a strongly typed model

I pass my model to my view. On this view I am displaying a table and trying to populate it with a list of information from the database.

I am using asp.net-mvc, entity framework, razor, c# and LINQ

However I need it grouped by a certain column kpiID.

Here are all of the columns in the table.

kpiHistoryID
kpiID
startAmount
completedamount
endAmount
completeBy
comments

The kpiID links back the the KPI table and is where I can grab the actual name of the KPI.

How exactly do I group the data and can it be done in the below @foreach line?

 <tbody>
    @foreach (var item in @Model.IPACS_Department.IPACS_Functions.SelectMany(m => m.IPACS_Processes).SelectMany(m => m.IPACS_Procedures).SelectMany(m => m.IPACS_KPIS).SelectMany(m => m.IPACS_kpiHistory))
    {
        <tr class="gradeX">
            <td>
                @item.IPACS_KPIS.name
            </td>
            <td>
                @item.startAmount
            </td>
            <td>
                @item.completedAmount
            </td>
            <td>
                @item.endAmount
            </td>
        </tr>
    }
</tbody>

Upvotes: 0

Views: 157

Answers (2)

James Wilson
James Wilson

Reputation: 5150

Only way I could figure out how to do it was using sum. Couldn't get it to work with group by at all.

<tbody>
    @foreach (var item in @Model.IPACS_Department.IPACS_Functions.SelectMany(m => m.IPACS_Processes).SelectMany(m => m.IPACS_Procedures).SelectMany(m => m.IPACS_KPIS))
    {
        <tr class="gradeX">
            <td>
                @item.name
            </td>
            <td>
                @item.IPACS_kpiHistory.Select(m => m.startAmount).Sum()
            </td>
            <td>
                @item.IPACS_kpiHistory.Select(m => m.completedAmount).Sum()
            </td>
            <td>
                @item.IPACS_kpiHistory.Select(m => m.endAmount).Sum()
            </td>
        </tr>
    }
</tbody>

Upvotes: 0

Colm Prunty
Colm Prunty

Reputation: 1620

This:

@Model.IPACS_Department.IPACS_Functions.SelectMany(m => m.IPACS_Processes)
.SelectMany(m => m.IPACS_Procedures).SelectMany(m => m.IPACS_KPIS)
.SelectMany(m => m.IPACS_kpiHistory)

gives a list of denormalised kpiHistories, yes? Does it not give you the answer you want if you do

thatList.GroupBy(x => x.kpiID)

Upvotes: 1

Related Questions