HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Optimization code for checking if a list contains any element ID of another list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
anycheckingoptimizationcontainsforelementanothercodelist

Problem

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
    .GetAllTrackerAttempts()
    .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));

Solution

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

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

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

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

Code Snippets

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);

Context

StackExchange Code Review Q#17636, answer score: 2

Revisions (0)

No revisions yet.