private DtDelta FindNextRelatedGroupDelta(DtDelta rootDtDelta, IEnumerable <DtDelta> allInserts, IEnumerable <DtDelta> allDeletes) { DtDelta result = null; if (rootDtDelta.Action == DtDelta.DeleteAction) { //get username for this deletion id var groupnameToDelete = string.Empty; var earlierInsert = allInserts. FirstOrDefault(i => i.Seq < rootDtDelta.Seq && i.DataAsGroup.Id == rootDtDelta.DataForDelete); if (earlierInsert != null) { groupnameToDelete = earlierInsert.DataAsGroup.Name; } //if there's no value in the array, there may be one in the db if (string.IsNullOrWhiteSpace(groupnameToDelete)) { groupnameToDelete = sqlService.GetGroupnameForId(rootDtDelta.DataForDelete); } //if you can't find a record for this Id, you can't proceed. Something is wrong with data. if (string.IsNullOrWhiteSpace(groupnameToDelete)) { throw new Exception(string.Format("No role insert record found for this id: {0}", rootDtDelta.DataForDelete)); } //search for next insert for same username as delete var insertsForGroupname = allInserts. Where(i => i.Seq > rootDtDelta.Seq && i.DataAsGroup.Name == groupnameToDelete) .OrderBy(a => a.Seq); if (insertsForGroupname.Any()) { result = insertsForGroupname.First(); } } else if (rootDtDelta.Action == DtDelta.InsertAction) { //search for delete action for same id var deletesForId = allDeletes. Where(i => i.Seq > rootDtDelta.Seq && i.DataForDelete == rootDtDelta.DataAsGroup.Id); if (deletesForId.Any()) { result = deletesForId.First(); } } return(result); }