Dictionary <K,V> question

  • Thread starter Thread starter amir
  • Start date Start date
A

amir

how can I access the first item of a dictionary where the datatype for the
Key is not known to me?

I tried the array index 0 and taht did not work because the key is not of
integer type.

Thanks in advance for all your help.
 
You don't need to know the datatype for the key to iterate through the
values.

Dictionary<string, string> myHash = new Dictionary<string,
string>();
myHash.Add("k1", "bob");
myHash.Add("k2", "jim");

foreach (string val in myHash.Values)
{
string firstValue = val;
break;
}
 
amir said:
how can I access the first item of a dictionary where the datatype for the
Key is not known to me?

What exactly do you mean by "first"? Dictionaries are inherently
unordered. You could use the enumerator to find the first value to come
out, but there's no guarantee that was the first which was put in.
I tried the array index 0 and taht did not work because the key is not of
integer type.

If you don't know the generic type parameters of the dictionary, how
are you accessing it? You may need to use reflection to get at the bits
of the item if you don't know the type parameters.
 
I knew of this one already but I was looking to see if a smarter and quicker
way existed.

Thanks much for your quick response
 
amir said:
I knew of this one already but I was looking to see if a smarter and quicker
way existed.

Thanks much for your quick response

There is no better way, as you can't access the items by index.

In framework 3.5 you can use one of the extension methods:

string firstValue = muHash.Values.First();

It does it the same way, though.
 

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