Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
How do you extract the key and value from an dictionary array using its index?
ex:

C#
Dictionary<int, double> ListPPM = new Dictionary<int, double>();
           ListPPM.Add(1, 445.1242);
           ListPPM.Add(4, 445.1992);
           ListPPM.Add(7, 445.1205);
           ListPPM.Add(22, 445.1205);
           ListPPM.Add(32, 445.1242);
           ListPPM.Add(34, 445.1992);
           ListPPM.Add(100, 445.1205);
           ListPPM.Add(157, 445.1205);


say I want ListPPM[2] which has key:7,445.1205
Posted
Updated 16-Aug-11 20:27pm
v2
Comments
#realJSOP 17-Aug-11 16:09pm    
DO NOT REPOST YOUR QUESTION. Your first version had an answer in it. The ONLY reason OI'm not deleting this question is because it's already got answers.

 
Share this answer
 
I'm not sure about the index here. What happens if you add the items into the list in different order? Do you want to get the third smallest key? Why I'm asking this is because SortedDictionary[^] guarantees that the items are sorted by the key.

So one possibility, if you want to use Dictionary, is to query the dictionary using LINQ and define the sorting in the statement. Something like:
C#
var q = from b in
               (from a in ListPPM
                orderby a.Key
                select a).Skip(2)
            select b;

q.First().Key;
 
Share this answer
 
you can access a dictionary's key by its ordinal in the key collection with the following:

C#
int index = 3;//or whatever you want
ListPPM.Keys.ElementAt<int>(index);


requires System.Linq namespace

EDIT : post format was messing up generic type
 
Share this answer
 
v4
C#
public sealed class CustomDictionary<tkey,TValue> : KeyedCollection<tkey,TValue>>
{
    protected override TKey GetKeyForItem(KeyValuePair<tkey,TValue> item)
    {
        return item.Key;
    }
    
}


C#
CustomDictionary<string,int> custDict = new CustomDictionary<string,int>(); 
CustDict.Add(new KeyValuePair<string,>("key", 7));
CustDict.Add(new KeyValuePair<string,>("key1", 8));
KeyValuePair<string,> i = CustDict[1];
int valueByIndex = CustDict[1].Value;
int valueByKey = CustDict["key"].Value;
string keyByIndex = CustDict[0].Key;

// Your requirment 
string skeyByIndex = CustDict[0].Key+","+CustDict[0].Value;
 
Share this answer
 
v2
Comments
#realJSOP 17-Aug-11 16:09pm    
You don't need to write ANY custom code for this. Just use an OredredDictionary, and you're all set.
Espen Harlinn 17-Aug-11 18:23pm    
OrderedDictionary is definitely the most elegant answer - I'd vote for it if it wasn't a comment :)
#realJSOP 17-Aug-11 18:38pm    
Well, I answered his first version of this question the same way. You can go vote for it there. :)

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