Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a dictionary which its keys are combination of several words (using join method)
I want to split them in a selected key. The selection is done by defining the index.
How can I refer to a key by its index?

What I have tried:

string text = music.Keys[2]
The code above cannot be compiled.
Posted
Updated 3-Feb-21 9:04am
Comments
PIEBALDconsult 3-Feb-21 14:40pm    
No, it doesn't work that way.
But you could also make a list or another Dictionary with the same values.
I often have to make several indices for some objects.

Indexes and Dictionaries aren't really much use: they aren't stored by any useful order, but by hash value. If you look at the source code: Reference Source[^]
and the Insert method (which Add calls) all indexing is done via a hashcode, which will not have any direct relation to the strings you are using as keys.

What I'd suggest is that you think of a different way to either store them, or access them - because even if you get code that works, you are setting yourself up for unpredictable and inconsistent results in the "real world".
 
Share this answer
 
music.ElementAt(2).Key;
 
Share this answer
 
v2
Comments
PIEBALDconsult 3-Feb-21 14:53pm    
Not necessarily repeatable? Items in a Dictionary have no inherent order.
RickZeeland 3-Feb-21 15:03pm    
You are probably right, but when it is done immediately after defining the dictionary it should work I think.
PIEBALDconsult 3-Feb-21 15:07pm    
Maybe, but it's still better to maintain an additional index -- possibly derive a new type of Dictionary with that ability cooked in.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900