views:

297

answers:

2

Hello,

I have Dictionary<long, Location> PostalCodes .

While i m adding new elements to this Dictionary I want to make a lookup to this dictionary and if the Location.PostalCode is not in this dictionary, I want to insert it. Otherwise I want to skip it. So , need to know if the PostalCode is already in the Collection. Cant use it as the key.

How to do this?

Thanks.

+4  A: 

You can try:

if(PostalCodes.Values.All(l=>l.PostalCode != location.PostalCode))
{
    PostalCodes.Add(key /*what is it*/, location);
}

But this might get slow with large amount of data.

Coincoin
s/might/will :)
Jon Skeet
+5  A: 

It sounds like you need another dictionary which does use it as the key - basically a bidirectional map. At least, that's if you want it to perform well. You could just look through every value in the map, but that would be an O(n) operation.

(Alternatively, if you're doing this once, just create a HashSet<Location> for all the locations you're using. You don't actually need the long, by the sounds of it for the purpose of the reverse lookup.)

Jon Skeet
Long is for External Location ID, it s a pointer to map the IP with Locations. So i have to use that. Also, I cant really use Postal Code as the key value of the Dict. because, I have seen that postalcodes are not unique for location. at least that s what the providers file shows.
But you *don't* have to use the long for the reverse lookup - that's what I meant. Will edit.
Jon Skeet