views:

186

answers:

2

I'm iterating through a List<> to find a matching element. The problem is that object has only 2 significant values, Name and Link (both strings), but has some other values which I don't want to compare.

I'm thinking about using something like HashSet (which is exactly what I'm searching for -- fast) from .NET 3.5 but target framework has to be 2.0. There is something called Power Collections here: http://powercollections.codeplex.com/, should I use that?

But maybe there is other way? If not, can you suggest me a suitable custom collection?

+2  A: 

In .NET 2.0 instead of a HashSet<T> you can use a Dictionary<K, V>.

Dictionary uses the hash code to perform key lookups so it has similar performace to the HashSet. There are at least two approaches:

  • Create a custom class or struct containing the Name and Link and use that as the key in the dictionary, and put the object as the value.
  • Store the entire object as the key and provide a custom equality comparer that only looks at the Name and Link member, and set the value to null.

The second method is very similar to how you would use a HashSet if it were available.

Mark Byers
Well I like the first option but isn't it worth writing a custom Collection?
Kaminari
@Kaminari Only if you want to reinvent the wheel. I think you're underestimating the speed of modern computers. Don't worry about optimization until it's an issue; you likely won't have to.
Ryan
@Ryan Yes it is an issue. I constantly checking my code performance and this time iteration took more than 6 seconds. I'm not worring if code is runing 10 or even 100ms slower, but 6 seconds is way too much.
Kaminari
Well based on your initial post's comment I'd say use a Dictionary with the key being the name + link assuming that is a unique combination. If it's still slow, it's likely just the size of the dataset. What did you change to cause it to slow down? What is a normal execution time?
Ryan
A: 

How about this:

Custom class/collection wich will held List of objects and two dictionaries, one for the name and one for the link. Both of them will have a int value wich will be the index of object. I think that in that case I will only need to check if there is such int value of name dictionary that equals link dictionary int.

Is this a good approach?

Kaminari
John Saunders
Hash the name and link together. Your proposed method requires two list traversals which I can't imagine is faster than doing a hash + one index lookup as in my comment above.
Ryan