Tomás Escamez
Tomás Escamez

Reputation: 552

Encapsulate LINQ GroupBy Select

I'm looking to encapsulate the Select section of the GroupBy to have a more readable, understandable and nicer code. There is anyway to do that?

This is what I have now (And I have a lot of GroupsBy in my code, is not only one, that's another reason to encapsulate as much as possible):

 var xTypeAggregatedTransactions = xTypeTrtansactions.
                    .GroupBy(x => new {x.TypeId, x.AccountId})
                    .Select(y => new PayTransactionsCommand
                    {
                        Id = Guid.NewGuid(),
                        Narration = item.Name,
                        AccountId = y.Key.AccountId,
                        Credit = y.Sum(z => z.Credit),
                    });

This is what I want:

var xTypeAggregatedTransactions = xTypeTrtansactions.
                                   .GroupBy(x => new {x.TypeId, x.AccountId})
                                   .AsEnumerable().ToPayTransaction();

Thanks

Upvotes: 2

Views: 122

Answers (1)

Backs
Backs

Reputation: 24913

Write an extension class:

public static class TypeTrtansactionExtensions
{
    public static IEnumerable<PayTransactionsCommand> ToPayTransaction(this IQueryable<TypeTrtansaction> query, string itemName)
    {
        return query.GroupBy(x => new { x.TypeId, x.AccountId })
                .Select(y => new PayTransactionsCommand
                {
                    Id = Guid.NewGuid(),
                    Narration = itemName,
                    AccountId = y.Key.AccountId,
                    Credit = y.Sum(z => z.Credit),
                });
    }
}

And call it:

var xTypeAggregatedTransactions = xTypeTrtansactions.ToPayTransaction(item.Name);

Also, you can add more parameters, if you need.

Upvotes: 1

Related Questions