Retrieving first key in Dictionary<T,T>

  • Thread starter Thread starter Beorne
  • Start date Start date
B

Beorne

I have to retrieve the first kei I have inserted in a
Dictionary<int,int> called dict.
The only method I found is:

Dictionary<int,int>.KeyCollection.Enumerator dke =
dict.Keys.GetEnumerator();
dke.MoveNext();
int first = dke.Current;

That seems a little convoluted, is there a more elegant way?
And, more importantly, can I be sure that this method retrieves the
first inserted key?

Note: I can't use SortedDictionary because I'm working on compact
framework.

Thanks
 
Beorne said:
I have to retrieve the first kei I have inserted in a
Dictionary<int,int>

I don't think you can do this. Dictionary<,> doesn't retain information
about the order of entry. Perhaps you could maintain a List<> that
contains the keys as they are inserted. Or, better, build your own
collection class that does this internally.
 
I don't think you can do this. Dictionary<,> doesn't retain information
about the order of entry. Perhaps you could maintain a List<> that
contains the keys as they are inserted. Or, better, build your own
collection class that does this internally.

--
Larry Lard
(e-mail address removed)
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version

thanks!
 
Beorne,

If you were not using generics, I would suggest using the SortedList as in:

SortedList dd = new SortedList();
dd.Add(2, 4);
dd.Add(4, 7);

int answer = (int) dd.GetByIndex(0);
MessageBox.Show(this, "Value: " + answer);

The draw back here being boxing, but you do get your key value pairs and
index access that you wanted.

Dave
 

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

Back
Top