Reputation: 2726
Here is piece of code which creates random data with different datetime.
void ExtractEveryXminute()
{
List<DataHolder> data = new List<DataHolder>();
List<DateTime> randomTimes = new List<DateTime>();
Random r = new Random();
DateTime d = new DateTime(2019, 9, 19, 7, 0, 0);
for (int i = 0; i < 100; i++)
{
DataHolder dh = new DataHolder();
TimeSpan t = TimeSpan.FromSeconds(r.Next(0, 14400));
dh.OID = i;
dh.Value = r.Next(50);
dh.Snapshottime = d.Add(t);
data.Add(dh);
}
data.OrderBy(o => o.Snapshottime).ToList();
List<DataHolder> SortedList = data.OrderBy(o => o.Snapshottime).ToList();
var query_res = (from s in SortedList group s by new DateTime(s.Snapshottime.Year, s.Snapshottime.Month, s.Snapshottime.Day, s.Snapshottime.Hour, 15, 0));
}
public class DataHolder
{
public int OID { get; set; }
public double Value { get; set; }
public DateTime Snapshottime { get; set; }
}
I need to get data apart let's say every 15 minutes. Now I'm getting only datetime at 07:15:00, 8:15:00, 9:15:00 but this is not correct. How to extract those date starting from first record in list and filter every 15 minutes?
Upvotes: 1
Views: 847
Reputation: 18155
You could use the following.
TimeSpan interval = new TimeSpan(0, 15, 0);
var result = SortedList.GroupBy(x=> x.Snapshottime.Ticks/interval.Ticks)
.OrderBy(x=>x.Key);
Sample Output
Update
If, as per the comment, you want only the first time from each group of 15 min interval, then you could use.
var result = SortedList.GroupBy(x=> x.Snapshottime.Ticks/interval.Ticks)
.Select(x=>x.First());
Upvotes: 3