views:

25

answers:

1

Hi,

I have 2 datagridviews (say, DGV-A and DGV-B) having just one column each. I want to find whether the item in DGV-A also exists in DGV-B. Basically, I am looking for a VLookup function available in MS-Excel. This can be done trivially, bus iterating over the values in DGV-A and for each iteration of DGV-A, iterate over DGV-B and see if it exists there (aborting iteration of DGV-B as soon as we have found the item exists). This needs to be done for all the items in DGV-A. And because my DGV's could potentially have around 200 items (e.g. if DGV contain 200 items each, at worst, I would be doing 200*200 = 40000 comparisions) in each datagridviews, I am afraid, it is not going to be quick.

Is there any way/algorithm to do it in an optimal way. (I do not have any data binding or database, so use of SQL/DB-Engine is not an option; my data in DGV's is generated programmatically on the fly based on the user actions)

+1  A: 

It is usually not a good idea to optimize code for performance until you know that you really have performance problems. But in this case I would use another solution, too, to avoid an O(n * m) operation.

I suggest to insert all items from one list into a hash set - this will be O(n) if you specify a large enough initial size and avoid resizing the hash set this way. Then just perform a look up in the hash set for each item in the second list in O(m). This way you get O(n * m) down to O(n + m).

Daniel Brückner