c# - Linq group by 与父对象

标签 c# linq

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

我有以下内容

        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 group by 与父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501910/

相关文章:

c# - 自定义列表框设计

c# - 使用 Linq to Sqlite (linq2db) 创建表

c# - Entity Framework 查询思路(group by)

c# - LINQ 可以用于搜索字符串中的多个 Regex 表达式吗?

c# - ReadProcessMemory - 缓冲区大小影响功能正确性

C# 如何从屏幕获取像素颜色/数据?

使用 Selenium 的 C# 代码覆盖率

c# - 将 C printf(%c) 转换为 C#

c# - 从 LINQ to XML 查询获取单个字符串

.net - 集合的参数/返回值应该是 IEnumerable<T> 还是 T[]?