简体   繁体   中英

LINQ GroupBy anonymous type and select timestamp that is within +/- one minute

I have a list of answers that i put into groups by matching the FormId then the ProductInstance and the lastly by TimeStamp like so:

var groups = answersForCustomerList.GroupBy(x => new { x.FormId, x.ProductInstance, x.TracingData.Timestamp });

which gives me groups like this:

FormId = {97748e5e-be41-4d53-9ef8-f0dc150e58b6}, ProductInstance = "kontot", Timestamp = {2016-12-20 16:00:00}
FormId = {87dd356b-2770-4427-89d2-7503ee80bb1c}, ProductInstance = "Lån", Timestamp = {2016-12-20 16:02:00} 
FormId = {87dd356b-2770-4427-89d2-7503ee80bb1c}, ProductInstance = "Lån", Timestamp = {2016-12-20 16:01:00} 
FormId = {97748e5e-be41-4d53-9ef8-f0dc150e58b6}, ProductInstance = "Konto", Timestamp = {2016-12-20 15:00:00}
FormId = {87dd356b-2770-4427-89d2-7503ee80bb1c}, ProductInstance = "Lån", Timestamp = {2016-12-20 15:59:00}

but what i need to do and cant seem to figure how is how to group timestamps that is within +/- 1 minute into the same group. So answers with the same FormId and ProductInstance but with TimeStamp 16:01:00 or 15:59:00 get in the same group as the 16:00:00 group.

I managed to sort-of get what i wanted with this:

 var groups = answersForCustomer
            .GroupBy(x =>
            {
                var stamp = x.TracingData.Timestamp;
                stamp = stamp.AddMinutes(-(stamp.Minute % 2));
                stamp = stamp.AddMilliseconds(-stamp.Millisecond - 1000 * stamp.Second);
                return new { stamp, x.FormId, x.ProductInstance };
            });

Which gives me groups with 2 minutes forward in time, thanks for all the answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM