使用linq按数组元素分组

时间:2013-07-18 09:26:15

标签: arrays linq group-by

我有以下结构中的数据,我需要按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) };

1 个答案:

答案 0 :(得分:-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()
                                        });