Kane
Kane

Reputation: 43

Speed Up Performance - LINQ to get items in one LIST, that are not in another List

I have two lists and I'm trying to return items that are not in the other list. Here is my code:

var Results = ListOne.Where(x => ListTwo.All(a => a.EmployeeNum != x.EmployeeNum && a.Sched != x.Sched));

This takes about 9-10 seconds to complete. ListOne has about 1200 records and ListTwo has about 33000 records.

Upvotes: 1

Views: 233

Answers (3)

Johnny
Johnny

Reputation: 9519

Using HashSet<T>, as it has O(1) search time could improve performances, e.g.

var hashSet = new HashSet<T>(ListTwo.Select(x => Tuple.Create(x.EmployeeNum, x.Sched)));
var results = ListOne.Where(x => !hashSet.Contains(Tuple.Create(x.EmployeeNum, x.Sched)));

Upvotes: 4

Stemado
Stemado

Reputation: 629

You can also create your own IEqualityComparer (assumes you have a class called Employee):

var results = ListTwo.Except(ListOne, new EmployeeComparer());

IEqualityComparer Implementation:

public class EmployeeComparer : IEqualityComparer<Employee>
{
    public int GetHashCode(Employee co)
    {
        if (co == null)
        {
            return 0;
        }

        return co.EmployeeNum.GetHashCode();
    }

    public bool Equals(Employee x1, Employee x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }

        if (object.ReferenceEquals(x1, null) || object.ReferenceEquals(x2, null))
        {
            return false;
        }

        return x1.EmployeeNum == x2.EmployeeNum && x1.Sched == x2.Sched;
    }
}

Upvotes: 2

Khaled Sameer
Khaled Sameer

Reputation: 306

try this

var Results = ListOne.AsParallel().Where(x => ListTwo.All(a => a.EmployeeNum != x.EmployeeNum && a.Sched != x.Sched)).ToList();

Upvotes: 0

Related Questions