I have two collections, each of which contains about 40,000 items.
Elements in list 2 are associated with elements of list 1 through a foreign key.
For each list item one, I want to find the corresponding item in list two.
Something like that:
foreach(var item in list1)
{
var match = list2.Where(child => child.ID == item.ChildID).FirstOrDefault();
item.Child = match;
}
It works, but it's slow as hell.
Now both lists1 and list2 are sorted by these keys from the database. Thus, list1 is sorted by ChildID, and list2 is sorted by ID (same value).
I think binary search would speed it up significantly, but I read somewhere that Linq will choose the most appropriate strategy for the list in the Where clause. Maybe I need to explicitly point to a sorted list? Or maybe I need to implement my own binary search algorithm with a comparator?
Any ideas appreciated.
Thanks.
Scott source
share