ichPotatodeCXY
ichPotatodeCXY

Reputation: 30

Group dateTime by hour range

I got a list like this:

class Article
{
...
Public DateTime PubTime{get;set}
...
}

List<Article> articles

Now I want to group this list with hour range :[0-5,6-11,12-17,18-23]

I know there is a cumbersome way to do this:

var firstRange = articles.Count(a => a.PubTime.Hour >= 0 && a.PubTime.Hour <= 5);

But I want to use a elegant way. How can I do that?Use Linq Or anything others?

Upvotes: 0

Views: 174

Answers (2)

IndieGameDev
IndieGameDev

Reputation: 2974

You could write a CheckRange Function, which takes your values and returns a bool. To make your code more reusable and elegant.

Function Example:

bool CheckRange (this int number, int min, int max) 
    => return (number >= min && number <= max);

You could now use this function to check if the PubTime.Hour is in the correct timelimit.

Implementation Example:

var firstRange = articles.Count(a => a.CheckRange(0, 5));

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Group by Hour / 6:

var grouped = articles.GroupBy(a => a.PubTime.Hour / 6);
IDictionary<int, int> CountsByHourGrouping = grouped.ToDictionary(g => g.Key, g => g.Count());

The key in the dictionary is the period (0 representing 0-5, 1 representing 6-11, 2 representing 12-17, and 3 representing 18-23). The value is the count of articles in that period.

Note that your dictionary will only contain values where those times existed in the source data, so it won't always contain 4 items.

Upvotes: 1

Related Questions