Get index from a Dictionary

L

Luigi

Hi all,
I have a Dictionary like this:

Dictionary<string, Object>

and I need to retrieve the index (0,1,2, etc) of a particular key (based on
dictionary insertion).

How can I accomplish this?

Thanks in advance.
 
J

Jon Skeet [C# MVP]

I have a Dictionary like this:

Dictionary<string, Object>

and I need to retrieve the index (0,1,2, etc) of a particular key (based on
dictionary insertion).

How can I accomplish this?

Dictionaries have no notion of insertion order - that information is
basically lost. If you need to maintain it, you'll need another data
structure (e.g. a list).

Jon
 
L

Luigi

Jon Skeet said:
Dictionaries have no notion of insertion order - that information is
basically lost. If you need to maintain it, you'll need another data
structure (e.g. a list).

Hi Jon,
and can I "pour" the keys collection of my Dictionary in a List, so I can
investigate the order of my strings?

Luigi
 
P

Peter Morris

and can I "pour" the keys collection of my Dictionary in a List, so I can
investigate the order of my strings?

No, you can inspect the order they were taken out of the dictionary and put
into the list. At best this will give you a current index; as soon as you
add a new value every index in the list could change, or non might.

What do you want to achieve?
 
L

Luigi

Peter Morris said:
No, you can inspect the order they were taken out of the dictionary and put
into the list. At best this will give you a current index; as soon as you
add a new value every index in the list could change, or non might.

What do you want to achieve?

My problem is that this dictionary serve a datasource of DevExpress
TreeList, and I have to write some tests that verify that the strings (the
keys in the dictionary) appear in a prestabilite order in that control (like
user preferences).

Luigi
 
P

Peter Morris

Create a facade class that acts as the data source. Inside that class have
both a List and a Dictionary that you maintain. Use the dictionary for
quickly locating items based on their key, and the list for determining
items at a specific index.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top