【问题标题】:Use linq to group by array element使用 linq 按数组元素分组
【发布时间】:2013-07-18 09:26:15
【问题描述】:

我有以下结构中的数据,我需要按 ID 和日期分组。日期是数组中的一个字段。我需要在顶层对按 Id 分组的每个日期的金额求和,这对 linq 是否可行?

Id 
Number 
MyArray[]

MyArray如下:

[Amount, Date]

尝试使用这样的东西,但它不会起作用,因为我的第二个分组是在主要项目的数组上

输入:

Id Number  MyArray
1    5     [{500.00,2001-03-08}, {200,2001-04-04}, {600, 2001-03-09}] 
2    6     [{700.00,2001-03-08}, {300,2001-03-08}]
1    7     [{400.00,2001-03-08}, {100, 2001-04-04}, {550.00,2001-12-12}]

预期结果:

  Id    MyArray
   1    [{500.00+400.00,2001-03-08}, {200+100,2001-04-04}, {600, 2001-03-09}, {550.00,2001-12-12}] 
   2    [{700.00,2001-03-08}, {300,2001-03-08}]

from s in db.Schedules

group s by new {s.empid, s.weekending} into g

select new { g.Key.empid, g.Key.weekending, g.Sum(s => s.hours) };

【问题讨论】:

  • 您能否提供一个示例输入和所需的输出?
  • @MarcinJuraszek - 我已经添加了输入和预期结果

标签: arrays linq group-by


【解决方案1】:
var results = db.Schedules.GroupBy(x => x.Id)
                          .Select(g => new
                                       {
                                           .Id = g.Key,
                                           .Data = g.SelectMany(x => x.MyArray)
                                                    .GroupBy(x => x.Date)
                                                    .Select(g2 => new { Amount = g2.Sum(x => x.Amount), Date = g2.Key })
                                                    .ToArray()
                                        });

【讨论】:

  • 谢谢!我可以将 .Data 设置为新的 MyArray 类型吗?所以匿名对象上有一个 MyArray 而不是数组 [DateTime, Decimal]
  • 这没有得到预期的结果,或者OP的例子是错误的。
  • @MarcinJuraszek - 如果我只需要按 MyArray 上的 Date 而不是 Id 分组,我可以这样做吗?努力让它工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多