C# 具有父对象的Linq group by

C# 具有父对象的Linq group by,c#,linq,C#,Linq,如何进行分组,以免丢失父标识符 我有以下几点 var grouped = mymodel.GroupBy(l => new { l.AddressId }) .Select(g => new { AddressId = g.Key.AddressId, Quotes = g.SelectMany(x => x.Quotes).ToList(),

如何进行分组,以免丢失父标识符

我有以下几点

        var grouped = mymodel.GroupBy(l => new { l.AddressId })
            .Select(g => new
            {
                AddressId = g.Key.AddressId,
                Quotes = g.SelectMany(x => x.Quotes).ToList(),
            }).ToList();
这是回报

{AddressId1,[Quote1,Quote2,Quote3…]}

{地址ID2,[Quote12,Quote5,Quote8…]}

现在我想按Quote.Code和Quote.Currency对它们进行分组,这样每个地址都有一个对象Quote(也就是说,如果属于该地址的所有4个引号都有相同的代码和货币)。我想要那个物体的货币总数

这是可行的,但我无法获得如何将地址添加到此结果:

        var test = grouped.SelectMany(y => y.Quotes).GroupBy(x => new { x.Code, x.Currency }).Select(g => new 
        {
            test = g.Key.ToString()
        });}
每当我尝试将AddressId添加到结果时,就会出现编译错误:

        var test1 = grouped.SelectMany(y => y.Quotes, (parent, child) => new { parent.AddressId, child }).GroupBy(x => new { x.Provider, x.Code, x.Currency, x.OriginalCurrency }).Select(g => new
        {
            test = g.Key.ToString(),
            Sum = g.Sum(x => x.Price)
        });
编译器错误:

        var test1 = grouped.Select(x => new { x.AddressId, x.Quotes.GroupBy(y => new { y.Provider, y.Code, y.Currency, y.OriginalCurrency }).Select(g => new
        {
            addr = x.AddressId,
            test = g.Key.ToString(),
            Sum = g.Sum(q => q.Price)
        };

我会这样做:

    var grouped = mymodel.GroupBy(l => new { l.AddressId })
        .Select(g => new
        {
            AddressId = g.Key.AddressId,
            QuotesByCode = g.SelectMany(x => x.Quotes)
                            .GroupBy(x=>x.Code)
                            .Select(grp=>new
                              {
                                Code = grp.Key.Code,
                                SumOfCurrency=grp.Sum(z=>z.Currency)
                              }).ToList(),
        }).ToList();

您是否可以显示(如您使用地址和引号所做的)预期结果?如果您想计算
货币
,那么
货币
在分组选项中做了什么?您应该只使用
code
对报价进行分组。好的,我已经计算了货币总额。但是如何添加AddressId呢?
Quotes=g.SelectMany(x=>x.Quotes).GroupBy(x=>x.code).Select(grp=>new{code=grp.Key.code,SumOfCurrency=grp.Sum(z=>z.Currency)}