我希望将GroupBy的Select部分封装起来,使其具有更易读,易懂和更好的代码。无论如何要做到这一点?
这就是我现在所拥有的(我的代码中有很多GroupsBy,不仅仅是一个,这是尽可能封装的另一个原因):
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),
});
这就是我想要的:
var xTypeAggregatedTransactions = xTypeTrtansactions.
.GroupBy(x => new {x.TypeId, x.AccountId})
.AsEnumerable().ToPayTransaction();
由于
答案 0 :(得分:1)
写一个扩展类:
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),
});
}
}
并称之为:
var xTypeAggregatedTransactions = xTypeTrtansactions.ToPayTransaction(item.Name);
此外,如果需要,您可以添加更多参数。