Markku Rintala
Markku Rintala

Reputation: 149

How to group dates by week and weekday with linq?

I have data from which I should count rows by weeks and weekdays. As result I should get

Starting day of the week, weekday, count of data for that day

I have tried this code:

var GroupedByDate = from r in dsDta.Tables[0].Rows.Cast<DataRow>()
                        let eventTime = (DateTime)r["EntryTime"]
                        group r by new
                        {
                            WeekStart = DateTime(eventTime.Year, eventTime.Month, eventTime.AddDays(-(int)eventTime.DayOfWeek).Day),
                            WeekDay = eventTime.DayOfWeek
                        } 
                        into g
                        select new
                        {
                            g.Key,
                            g.WeekStart,
                            g.WeekDay,
                            LoadCount = g.Count()
                        };

However, from DateTime(eventTime.Year, ...) I get an error "C# non-invocable member datetime cannot be used like a method."

What to do differently?

Upvotes: 0

Views: 1046

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

The immediate error is due to you missing the new part from your constructor call. However, even with that, you'd still have a problem as you're using the month and year of the existing date, even if the start of the week is in a previous month or year.

Fortunately, you can simplify it very easily:

group r by new
{
    WeekStart = eventTime.AddDays(-(int)eventTime.DayOfWeek)),
    WeekDay = eventTime.DayOfWeek
}

Or if eventTime isn't always a date, use eventTime.Date.AddDays(...).

Alternatively, for clarity, you could extract a separate method:

group r by new
{
    WeekStart = GetStartOfWeek(eventTime)
    WeekDay = eventTime.DayOfWeek
}

...

private static DateTime GetStartOfWeek(DateTime date)
{
    // Whatever implementation you want
}

That way you can test the implementation of GetStartOfWeek separately, and also make it more complicated if you need to without it impacting your query.

Upvotes: 6

Related Questions