gpt4 book ai didi

c# - Linq 分组依据与父对象

转载 作者:行者123 更新时间:2023-11-30 23:24:59 25 4
gpt4 key购买 nike

如何分组才能不丢失父标识符。

我有以下内容

        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...]}

{ AddressId2, [Quote12, Quote5, Quote8...]}

现在我想按 Quote.Code 和 Quote.Currency 对它们进行分组,这样每个地址都有 1 个对象报价(也就是说,如果属于该地址的所有 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();

关于c# - Linq 分组依据与父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com