C# 如何在linq中展平GroupBy和选择

C# 如何在linq中展平GroupBy和选择,c#,linq,C#,Linq,我有一个查询,它返回一些分组数据,我在如何“展平”它以使每个组都可以获得顶级信息上画了一个空白 Account A - Group A - Group B - Group C - etc Account B - Group B - Group C 我想做的是将其“展平”到: 这是我到目前为止得到的,但我不完全确定该去哪里 var transactions = Accounts.Where(clause) .Select(x =>

我有一个查询,它返回一些分组数据,我在如何“展平”它以使每个组都可以获得顶级信息上画了一个空白

Account A
    - Group A
    - Group B
    - Group C
    - etc

Account B
    - Group B
    - Group C
我想做的是将其“展平”到:

这是我到目前为止得到的,但我不完全确定该去哪里

var transactions = Accounts.Where(clause)
    .Select(x => new
    {
        Account = x,
        TransGroupedByBucket = x.TransactionLogs.GroupBy(tl => tl.TransactionType.BucketTypeID)
    })

    //pseudocode
    //Select  new {
    //   Account,
    //   One_TransactionLog_Group
    //}

    //will run for each group:
    .Select(x => new
    {
        AccountInfo = x.Account.ID
        Sum = One_TransactionLog_Group.Sum(tl => tl.Amount)
    })
    ;

我想我只是在放屁,有人能告诉我正确的方向吗?我的一个想法是从
TransactionLog
级别开始翻转它,然后遍历到
帐户
,但是
帐户
可能有0个
TransactionLog
,因此可能无法正常工作。

您可以使用
选择多个

Accounts.SelectMany(x => x.TransactionLogs.
                           Select(y => new { Account = x.ID,
                                             TransactionLog = y,
                                             Sum = ... });

Accounts.SelectMany(x=>returnx.TransactionLogs.Select(y=>new{Account=x.ID,TransactionLog=y,Sum=…}))
我想这就是我要找的。我想我在想有一种方法可以在“顶层”进行最终选择,但我想它们必须在
SelectMany
中。是的,如果你想写下答案的话,我就这么做了。谢谢你的帮助当然,完成了,很高兴我能帮上忙:)再次感谢。我知道这是一个带有
SelectMany
的东西,但我没有考虑将最后一个select作为
SelectMany
的“子查询”,这是我缺少的部分。
Accounts.SelectMany(x => x.TransactionLogs.
                           Select(y => new { Account = x.ID,
                                             TransactionLog = y,
                                             Sum = ... });