public async Task <Report> AddReportAsync(Report report) { List <Event> events = _dal.GetEvents(e => e.StartTime <= EntityFunctions.AddMinutes(report.Time, 5).Value&& e.EndTime >= EntityFunctions.AddMinutes(report.Time, -5).Value).ToList(); /*(from e in GetEvents() * where e.StartTime <= report.Time.AddMinutes(10) && * e.EndTime >= report.Time.AddMinutes(-10) * select e).ToList();*/ if (events.Count == 1) { Event e = modifyEvent(events[0], report); UpdateEvent(e); report.Event = e; } else if (events.Count > 1) { Event closestEvent = events[0]; // initialize pointer for compare later double tmpInterval, minInterval = Math.Abs((report.Time - closestEvent.StartTime).TotalMinutes); foreach (Event ev in events) // check closest start time { tmpInterval = Math.Abs((report.Time - ev.StartTime).TotalMinutes); if (tmpInterval < minInterval) { minInterval = tmpInterval; closestEvent = ev; } } foreach (Event ev in events) // check closest end time { tmpInterval = Math.Abs((report.Time - ev.EndTime).TotalMinutes); if (tmpInterval < minInterval) { minInterval = tmpInterval; closestEvent = ev; } } Event e = modifyEvent(closestEvent, report); //after check with all the end and the start events we found the closest event. UpdateEvent(e); report.Event = e; } else// event.count == 0 { report.Event = new Event(report.Time) { StartTime = report.Time }; } var res = await _dal.AddReportAsync(report); UpdateHits(report); return(res); }