0

I have a Model with a List of Transactions. Each Transaction has Category and Transaction Amount.

In my view page, I am creating a table from the Model which shows in each row of the table:

Category1 - SumofTransactionAmounts1

Category2 - SumofTransactionAmounts2

Category3 - SumofTransactionAmounts3

I am able to achieve this. However, how can i order the rows by ascending/ descending order of SumofTransactionAmounts?

    @foreach (var item in Model.MyTransactions.groupby(x => x.Category).ToList())
{
<tr>
<td>@item.key</td>
<td>@Model.MyTransactions.Where(x => x.Category == item.key).ToList().Sum(x => x.TransactionAmount)</td>
</tr>
}
  • The trick here would be to `Select` the group info, the `Sum` and apply the `Order` in your `foreach` statement. (I am on mobile, so I am not able to provide you with the full example) – Stefan Nov 26 '19 at 05:42
  • refer [this](https://stackoverflow.com/questions/6601715/how-to-declare-a-local-variable-in-razor) create local List in Razor View to group by category, then `foreach` on that list – Sushant Yelpale Nov 26 '19 at 05:45

2 Answers2

0

You can achieve it by ordering the IEnumerable<IGrouping<>> like this:

@foreach (var item in Model.MyTransactions.GroupBy(x => x.Category).OrderBy(g => g.ToList().Sum(i => i.TransactionAmount)))
{
    <tr>
        <td>@item.key</td>
        <td>@item.ToList().Sum(x => x.TransactionAmount)</td>
    </tr>
}
ravi kumar
  • 1,548
  • 1
  • 13
  • 47
0

Create Local List in Razor Page Something Like This,

@{var ListItems = (Model.MyTransactions.groupby(x => x.Category).select(item => new {
    Category = item.key,
    Sum = item.Sum(x => x.TransactionAmount)
}).OrderBy(e=> e.Sum).ToList();}

Use it in ForEach

@foreach (var item in ListItems)
{
    <tr>
    <td>@item.Category</td>
    <td>@item.Sum</td>
    </tr>
}

This Way you can access ListItems anywhere on page

Sushant Yelpale
  • 860
  • 6
  • 19