ThomasG
ThomasG

Reputation: 129

LINQ filtering between two times and by hour

I have a LINQ query that is currently like this:

var query = from l in Records
            where l.time >= time1 && l.time <= time2
            select l;

however, the Records collection used to log once every two seconds, now it logs once an hour. I need a way of only grabbing one Record an hour from the old data, so that the returned data makes more sense, and so I don't return months of data logged every 2 seconds...Any help would be great.

Upvotes: 2

Views: 4241

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

So you want only one record per hour. That means you need to group by hour:

var query = records
            .Where(r => r.time >= time1 && r.time <= time2)
            .Select(r => new
            {
                Hour = new DateTime(r.time.Year, r.time.Month, r.time.Day, r.time.Hour, 0, 0),
                Record = r
            })
            .GroupBy(x => x.Hour)
            .Select(grp => grp.First().Record);

Upvotes: 4

david.s
david.s

Reputation: 11403

You should group by hour and select the first element for each hour.

Try this:

var query = from l in Records
            where l.time >= time1 && l.time <= time2
            group l by l.time.Hour into g
            select g.First();

Upvotes: 1

Related Questions