开发者

LINQ: How to perform a conditional sum?

I have a LINQ Query that creates a new type that contains a days of week and a sum of hours worked. My current (incorrect query) looks like this:

var resultSet = (from a in events
                 group a by a.Start.DayOfWeek into g
                 select new DaySummary
                 {
                     day = g.Key.ToString(),
                     hoursWorked = g.Any(p => p.Title == "Lunch") ? 0 :
                     Math.Round((g.Sum(
                     p => (Decimal.Parse((p.End - p.Start).TotalMinutes.ToString()))) / 60), 2)
                 }).ToList();

Hopefully you can see what Im trying to do. The Any method is not having the开发者_运维知识库 effect I'd like however. Basically I want to to sum up the hours worked, but if the title was "lunch" I want it to add 0.

The logic of this is just a little beyond me at the moment.

UPDATE Ok, Im an idiot. Changes the query to this and it now works. Sorry.

var resultSet = (from a in events
                             group a by a.Start.DayOfWeek into g
                             select new DaySummary
                             {
                                 day = g.Key.ToString(),
                                 hoursWorked = Math.Round((g.Where(p => p.Title !="Lunch").
                                 Sum(p => (Decimal.Parse((p.End - p.Start).TotalMinutes.ToString()))) / 60), 2)                                    
                             }).ToList();


It seems each group is a sequence of 'periods' and you just want to ignore any 'lunch' periods in each calculation. In that case you just need to remove these from the sum using Where.

var hours = events
    .GroupBy(e => e.Start.DayOfWeek)
    .Select(g => new DaySummary {
        day = g.Key.ToString(),
        hoursWorked = Math.Round(
            g.Where(p => p.Title != "Lunch")
            .Sum(pd => (Decimal.Parse((pd.End - pd.Start).TotalMinutes.ToString())) / 60), 2)
    }).ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜