C# 通过选择封装LINQ GroupBy

C# 通过选择封装LINQ GroupBy,c#,linq,C#,Linq,我希望封装GroupBy的Select部分,以获得更可读、更易理解和更好的代码。有什么办法可以做到这一点 这就是我现在拥有的(我的代码中有很多GroupsBy,这不仅仅是一个,这也是尽可能多地封装的另一个原因): 这就是我想要的: var xTypeAggregatedTransactions = xTypeTrtansactions. .GroupBy(x => new {x.TypeId, x.AccountId})

我希望封装GroupBy的Select部分,以获得更可读、更易理解和更好的代码。有什么办法可以做到这一点

这就是我现在拥有的(我的代码中有很多GroupsBy,这不仅仅是一个,这也是尽可能多地封装的另一个原因):

这就是我想要的:

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

谢谢

写一个扩展类:

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),
                });
    }
}

此外,如果需要,您可以添加更多参数。

不要认为这是可能的,因为您正在使用匿名类型进行分组。你可以尝试做一些基于反射的东西,创建表达式树manuall,但这不是一个简单的解决方案。问题是,
new{x.TypeId,x.AccountId}
是一个匿名类型,所以你不能将它传递给一个知道如何处理它的方法……这里面的
item
是什么,匿名类型是@ThomasLevesque的问题。项目是另一个实体,我在byI小组之前就考虑过这个问题,但我想知道是否有其他方法可以做到这一点。无论如何,我会把这个标记为答案,因为似乎没有其他解决方案!Thanks@TomásEscamez这种方式是最常见的,我最终选择了这种方式,谢谢@Backs。只是一个小细节,这里没有必要使用.AsEnumerable(),如果您正在阅读,请避免使用它@TomásEscamez是的,有时需要一个可计算的,如果您进行复杂的转换,这在sqlyes中是无法完成的。当然,有时您可能需要它。但在这个例子中是无用的,这就是我想说的。
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);