Hey All,
I'm using VS 2005 fx2.0.
If I know my Dictionary contains only 1 item how do I get to it?
Thanks, rod
Hey All,
I'm using VS 2005 fx2.0.
If I know my Dictionary contains only 1 item how do I get to it?
Thanks, rod
Make sure you have using System.Linq;
. The below command will get the key value pair of the dictionary
var item = Dictionary<k,v>.Single();
var key = item.Key;
var value =item.Value;
Ngu Soon Hui is correct but to be a bit safer (in the event that there is more than one item) you could do this:
yourDictionary.First();
And to be even safer you could do this (in the event that the dictionary was empty as well):
yourDictionary.FirstOrDefault();
The only way (with framework 2.0) is to iterate over it with foreach.
Or make a method that do that, like:
public static T GetFirstElementOrDefault<T>(IEnumerable<T> values)
{
T value = default(T);
foreach(T val in values)
{
value = val;
break;
}
return value;
}
It works with all IEnumerable and in your case T is KeyValuePair
Just iterate over all elements of Dictionary (in this case only one)
foreach (KeyValuePair<v, k> keyValue in dictionary)
{
}