首页 > 解决方案 > Summing by multiple columns in a list

问题描述

I am creating a html table to display values in a List<> the list has three columns: the name of the indicator, the year and month in which it was selected and the count of the number of times it has been filtered on.

the code and html I am using is shown below:

<table class="users">
    <tr>
        <th></th>
        @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
        {
            <th>@monthYear</th>
        }
    </tr>
    @foreach (var keyIndicator in Model.KeyIndicatorUseCount.Select(m => m.Name).Distinct())
    {
        <tr>
            <td>@keyIndicator</td>
            @foreach (var monthYear in Model.KeyIndicatorUseCount.Select(m => m.MonthYear).Distinct())
            {
                <td>@Model.KeyIndicatorUseCount.Sum(m => m.Count)</td>
            }
        </tr>
    }
</table>

Currently the table is being populated with the sum of the values for the first month-year column.

The calculation needs to be the sum of the number of views for each key indicator with that month-year.

For reference here is a screenshot of what is currently being produced:

Key indicator counts by month

How do I go about performing the calculation to get a sum which corresponds to each month-year for the key indicator name in the first column?

标签: c#listlinqrazor

解决方案


 @foreach (var keyIndicator in item.OrderBy(f => f.Name).GroupBy(f => f.Name))
 {
     <tr>
         <td>@keyIndicator.Key</td>
         @foreach (var monthYear in keyIndicator.OrderBy(f => f.MonthYear).GroupBy(f => f.MonthYear))
         {
              <td>@(keyIndicator.Sum(f => f.Count))</td>
         }
         <td>
             @(keyIndicator.Sum(f => f.Count)) /* if you want to sum count of every month of year */
         </td>
     </tr>
}

推荐阅读