Select objects from a collection with same property values

Is there an easy way to select the members with same currencyId's so I can sum them with each other, or do I need to do else if for every currencyId there is ?

if(model.CurrencyId == -1)
        {
            resultModel.Add(new ReportModel
            {
                AccountName = "Sum",
                BalanceSum = resultModel.Where(q => q.CurrencyId == 1).Sum(q => q.Balance)

            });
        }
        else
        {
            resultModel.Add(new ReportModel
            {
                AccountName = "Sum",
                BalanceSum = resultModel.Sum(q => q.Balance)

            });
        }

Upvotes: 0

Views: 159

Answers (1)

Greg
Greg

Reputation: 4518

To get the sum of the balance for each currency, you can preform groupBy, followed by select & sum.

E.g:

var balanceSum = t.GroupBy(q => q.CurrencyId)
    .Select(q => q.Sum(x => x.Balance));

To add it to the resultModel, you can do something like:

var reportData = t.GroupBy(q => q.CurrencyId)
    .Select(q => new ReportModel()
    {
        AccountName = "Sum",
        BalanceSum = q.Sum(x => x.Balance)
    });

resultModel.AddRange(reportData);

If the data is only assigned to resultModel once, then you can probably replace AddRange with equals.

Upvotes: 2

Related Questions