Optimization code for checking if a list contains any element ID of another list I have the following code:

var sessionsWithError = SessionsFilteredByDate
    .Where(i =&gt; i.TrackerId &gt; 0 &amp;&amp; i.StatusId == 0)
    .Select(i =&gt; i.SessionId);
var sessionsWithErrorFixed = BusinessClient.Instance.Tracker
    .GetAllTrackerAttempts()
    .Select(i =&gt; 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 =&gt; sessionsWithErrorsNotFixed.Any(y =&gt; y == i.SessionId));
Put the values into a HashSet&lt;T&gt; (see here) as the lookup for that is constant O(1).

var sessionsWithErrorSet = new HashSet&lt;int&gt;(
    SessionsFilteredByDate.Where(i =&gt; i.TrackerId &gt; 0 &amp;&amp; i.StatusId == 0).Select(i =&gt; i.SessionId));

var sessionsWithErrorFixedSet = new HashSet&lt;int&gt;(
    BusinessClient.Instance.Tracker.GetAllTrackerAttempts().Select(i =&gt; i.SessionId));

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