Getting First Key in a Dictionary

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have the following:

Dictionary<object, string> d = new Dictionary<object, string>();

I can add entries to the dictionary, and I can loop through the entries I've
added to the Dictionary. This all works great.

My question is: I'd like to find a way to get just the first key, without
looping through the whole Dictionary. I tried the code below, but I get a
compile error trying to use an index value [0] on the KeyCollection:

Dictionary<object, string>.KeyCollection keyColl = d.Keys;
object firstStyle = keyColl[0];

Any suggestions?

Thanks,
 
OK - why you say "first", do you mean in insertion sequence? I'm not sure
this is retained in a dictionary...

Anyways, since the key-collection it is enumerable:

foreach(object key in keyCol) {
return key; or assign to a variable and then "break;"
}
// if here, then no key to get... oops!

Marc
 
Actually, it occurs that null keys are not allowed, so the following would
be quite tidy:

object firstKey = null;
foreach(object key in d.Keys) {
firstKey = key;
break;
}
// now if firstKey == null, no keys, else it is the first

Marc
 
Many thanks for the response. That's what I need.

You do raise an interesting question about whether the insertion sequence is
preserved. So far in my testing, it seems to be. Still, if it's not
guarenteed, I need to switch to a List<MyContainerClass>.

Does anybody know for sure if a Dictionary preserve the insertion sequence?

Thanks,
 
To quote from MSDN2 "The order of the keys in the Dictionary.KeyCollectionn
is unspecified"...

Also - if you always want the first one, you might want a Queue<T>

Marc
 
Actually - worth another note at this juncture re Queue<T> vs List<T>; now,
I don't know for sure with List<T>, but ArrayList (its older brother) was
known for *not* reclaiming empty space from removed elements - so if you
keep adding and removing elements then actually the underlying array keeps
growing (via doubling) inline with the total number of elements added. As I
understand it, Queue<T> does not suffer this, as the fact that we are always
removing items from the start makes it easy to reclaim space. But I honestly
don't know how List<T> behaves here ;-p

Marc
 

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