在 linq 中选择总小时数
这很难解释,但我会尝试 我有一个包含一些字段的表,并且该表有包含行的子表(我不是在谈论 SQL,它是 DB4O,但我使用 linq)。行有 timefrom
和 timeto
,例如:
maintable:
Description,
CreateDate,
....
mainTableRows:
08:00,
09:00,
some description
现在我需要进行一个查询,对行中的小时数进行求和,如下所示:
09:00-08:00 = 1hour(first row) + 10:00-09:00 (second row)
等等。
类似于:
var item = from mainTable m
select new
{
m.Id,
Hours = m.Rows.Sum(c=> new { Hour = c.TimeTo - c.TimeFrom })
}
感谢大家的帮助,这是我的完整解决方案:
var item = from mainTable m
select new
{
m.Id,
Hours = String.Format("{0:HH:mm}", (new DateTime((p.TimesheetRows.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal += (t.TimeTo - t.TimeFrom)).Ticks))))
}
It will be hard to explain but I'll try
I've got a table with some fields, and that table got subtable with rows (I'm not talking about SQL, its DB4O, but I use linq). Rows got timefrom
and timeto
, example:
maintable:
Description,
CreateDate,
....
mainTableRows:
08:00,
09:00,
some description
Now I need to make a query that will sum hours from rows, like this:
09:00-08:00 = 1hour(first row) + 10:00-09:00 (second row)
and so on.
Something like:
var item = from mainTable m
select new
{
m.Id,
Hours = m.Rows.Sum(c=> new { Hour = c.TimeTo - c.TimeFrom })
}
Thanks all for help, this is mine full solution:
var item = from mainTable m
select new
{
m.Id,
Hours = String.Format("{0:HH:mm}", (new DateTime((p.TimesheetRows.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal += (t.TimeTo - t.TimeFrom)).Ticks))))
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你想要总的经过时间,你可以这样做:
If you want the total elapsed time, you can do:
如果我理解正确的话,你就很接近了。选择之后才可以进行聚合。
If I understand you correctly you are pretty near. Only the aggregation could be made after the selection.
假设 Rows 是某种
IEnumerable
,如果您也想要小数小时,则可以这样做:或者如果您想要整数小时的总和,则可以这样做:
Assuming Rows is some sort of
IEnumerable<T>
, you can do this if you want fractions of hours too:Or this if you want the sum of whole-number hours:
(c.TimeTo - c.TimeFrom)
的类型为 TimeSpan:(c.TimeTo - c.TimeFrom)
is of type TimeSpan: