fyodorfranz
fyodorfranz

Reputation: 486

Optimizing a linq query for collecting matching objects from two lists

I have two lists of objects (list 1 and list 2) and I need to create a third list of objects from list 1 that share a property value with at least one object from list 2. I created the following linq query to do this, however, it is quite slow (in large part, no doubt, because the two starting lists can contain up to 200,000 objects).

(from obj1 in _list1
 from obj2 in _list2
 where obj1.SpecialId == obj2.SpecialId
 select obj1)
.ToList();

Is there a more efficient way to implement this in code (perhaps without using linq in the first place)?

Upvotes: 0

Views: 297

Answers (1)

monoh_
monoh_

Reputation: 1039

You can use LINQ Join to do this.

Query syntax:

var result = (from obj1 in _list1
            join obj2 in _list2 on obj1.SpecialId equals obj2.SpecialId
            select obj1
            ).ToList();

Method syntax:

var result = _list1.Join(_list2, obj1 => obj1.Id, obj2 => obj2.Id, (obj1, obj2) => obj1).ToList();

According to my simple tests, version with Join is about 5-6 times faster than Your original version.

Upvotes: 5

Related Questions