【问题标题】:How can i Join, GroupBy and Select with LINQ?如何使用 LINQ 加入、GroupBy 和选择?
【发布时间】:2021-12-23 10:05:07
【问题描述】:

我正在尝试执行 Join、GroupBy 两列并选择新列表作为

            var v = master.Join(
                detail,
                o => o.Id,
                d => d.OrderId,
                (o, d) => new 
                {
                    DateAdded = o.DateAdded,
                    VatRate = d.VatRatePercentage,
                    InvoiceDescription = o.InvoiceDescription
                }).GroupBy(c => new
                {
                    c.DateAdded,
                    c.VatRate
                })
                .Select(gcs => new 
                {
                    DateAdded = gcs.Key.DateAdded.Date,
                    VatRate = gcs.Key.VatRate,
                    InvoiceTypeDescription = gcs.Key.InvoiceDescription,
                }
                ).ToList();

但我得到了错误

'<anonymous type: DateTime DateAdded, decimal VatRate>' does not contain a definition for 'InvoiceTypeDescription' and no accessible extension method 'InvoiceTypeDescription' accepting a first argument of type '<anonymous type: DateTime DateAdded, decimal VatRate>' could be found

我想按两列(DateAdded、VatRate)进行分组,但同时在结果中获取 InvoiceDescription 列。我该如何解决?

【问题讨论】:

  • 您是否意识到gcs 是一组具有相同DateAddedVatRate 的事物的,但可能具有不同的InvoiceDescriptions?现在知道了,哪个 InvoiceDescription 想要从每个组中获得?
  • 你这是什么意思?我希望在 GroupBy 子句之前从连接结果中获得发票描述
  • 你能展示一些示例输入和输出吗?我在说Select 子句中的“从连接结果中获取发票描述”是没有意义的。

标签: c# linq


【解决方案1】:

这是一个示例:

var resultmutiplekeylambaorderbyelement = studentlist  
    .GroupBy(stu => new{stu.standard, stu.age})  
    .OrderBy(g => g.Key.standard).ThenBy(y=> y.Key.age)  
    .Select(g => new { standardkey = g.Key.standard, agekey = g.Key.age, studentobj = g.OrderBy(y => y.name) });

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多