开发者

select sum hours in linq

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 n开发者_C百科eed 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))))
                 }


If you want the total elapsed time, you can do:

 var item = from mainTable m 
       select new
         { 
           m.Id, 
           Hours = m.Rows
                    .Select(c => c.TimeTo - c.TimeFrom)
                    .Aggregate( (working, next) => working.Add(next) )
                    .TotalHours
         }


If I understand you correctly you are pretty near. Only the aggregation could be made after the selection.

private class TestData 
{
    public DateTime from;
    public DateTime to;
}

public static test()
{
   Collection<TestData> x = new Collection<TestData>();
   x.Select(item => (item.to - item.from).Hours).Sum();
}


Assuming Rows is some sort of IEnumerable<T>, you can do this if you want fractions of hours too:

var item = from mainTable m 
           select new
             { 
               m.Id, 
               Hours = m.Row.Sum(c => (c.TimeTo - c.TimeFrom).TotalHours) 
             }

Or this if you want the sum of whole-number hours:

var item = from mainTable m 
           select new
             { 
               m.Id, 
               Hours = m.Row.Sum(c => (c.TimeTo - c.TimeFrom).Hours)                 
             }


(c.TimeTo - c.TimeFrom) is of type TimeSpan:

var item = from m in mainTable 
           select new { m.Id, Hours = m.Rows.Sum(c => (c.TimeTo - c.TimeFrom).TotalHours)};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜