What I would do is loop thru the line items first and get the information that you need for the search, which in this case is the item internal id. After collecting the internal ids, do your search once, then loop thru the lines again to update it as needed.