tags:

views:

64

answers:

1

In my OrderedDictionary I want to replace an object. I saw that the OrderedDictionary has a method called Insert(). So, I thought when I get the index of the object I want to replace, I remove that object with RemoveAt() and then insert the new object with the Insert() method.

But... I need to figure out what the index is of the object I want to replace. Should I simply use a for loop or is there a better way?

Some background information: This piece of code is put into a method. And the method can be called multiple times in a for loop in another method.

+2  A: 

If you know the key of the target entry you can do it like this:

myOrderedDictionary["keyToReplace"] = "modifiedValue";

Otherwise, you will have to loop to locate the target before replacing it.

If you only have the target object in hand you can gets its index by looping through the Values field, but be aware that it's legal for there to be duplicates here (though not in Keys).

Steve Townsend
haha that easy. I thought it was read only. Guess I was wrong =]
Martijn
@Martijn: If it was read-only, how could you expect to use `RemoveAt` and `Insert`?
Timwi
@Timwi: Haven't thought about that..
Martijn