I have the following code:

var sessionsWithError = SessionsFilteredByDate
    .Where(i => i.TrackerId > 0 && i.StatusId == 0)
    .Select(i => i.SessionId);
var sessionsWithErrorFixed = BusinessClient.Instance.Tracker
    .Select(i => i.SessionId);
var sessionsWithErrorIntersection = sessionsWithError.Intersect(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.Except(sessionsWithErrorIntersection);

Then I have to create a IEnumerable where I put all the SessionsFilteredByDate where the sessionID is included in sessionsWithErrorsNotFixed, but this operation, since I am using the Any operator, it's slow, apparently \$O(m*n)\$.

How can I achieve this operation with a lower complexity?

SessionsFilteredByDateAndErrors = SessionsFilteredByDate
    .Where(i => sessionsWithErrorsNotFixed.Any(y => y == i.SessionId));

1 Answer 1


Put the values into a HashSet<T> (see here) as the lookup for that is constant O(1).

var sessionsWithErrorSet = new HashSet<int>(
    SessionsFilteredByDate.Where(i => i.TrackerId > 0 && i.StatusId == 0).Select(i => i.SessionId));

var sessionsWithErrorFixedSet = new HashSet<int>(
    BusinessClient.Instance.Tracker.GetAllTrackerAttempts().Select(i => i.SessionId));

var sessionsWithErrorIntersection = sessionsWithError.IntersectWith(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.ExceptWith(sessionsWithErrorIntersection);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.