views:

252

answers:

1

I am considering of using the OrderedDictionary. As a key I want to use a long value (id) and the value will be a custom object.

I use the OrderedDictionary because I want to get an object by it's Id and I want to get an object by it's 'collection' index.

I want to use the OrderedDictionary like this:

public void AddObject(MyObject obj)
{
  _dict.Add(obj.Id, obj); // dict is declared as OrderedDictionary _dict = new OrderedDictionary();
}

Somewhere else in my code I have something similar like this:

public MyObject GetNextObject()
{
  /* In my code keep track of the current index */

  _currentIndex++;
  // check _currentindex doesn't exceed the _questions bounds
  return _dict[_currentIndex] as MyObject;
}

Now my question is. In the last method I've used an index. Imagine _currentIndex is set to 10, but I have also an object with an id of 10. I've set the Id as a key.

The Id of MyObject is of type long?. Does this goes wrong?

+1  A: 

Updated as I never noticed the OrderedDictionary part! The indexer has an override of either object which will retrieve the value by key, or int which will retrieve the value by index. You would need to cast your index as an object if you are looking to retrieve it by key e.g.

_dict[(object)_currentIndex] as MyObject;
James
So when I pass _currentIndex it sees that it is an int and therefore it knows to look for the index and not for id, because the id of type long?. ?
Martijn
@Martin, sorry I never noticed you were using an `OrderedDictionary` please see my updated answer.
James
No problem. But _currentIndex is an int and used to get MyObject by index and not by Id. SO I suppose I don't have to cast _currentIndex? I only have to cast the indexer when I want MyObject by id, right?
Martijn
@Martijn: Ah I thought you were looking to retrieve it by ID and it kept doing it by index. In that case then no you shouldn't have to do any casting as long as the value you are passing is is explicitly an integer it should be fine.
James
Aah okee, the OrderedDictionary is smart enough to determine what I want: get the object by Id or by index, because of the value types..?
Martijn
@Martijn: Yes, see http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx
James
Thnx. I've read that page, but I could not find the part where it is mentioned.
Martijn