views:

105

answers:

5

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

+5  A: 

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
The question is about VS2005. To use linq you'll need VS2008 with fx3.5
Michał Piaskowski
A: 
dictionary.SingleOrDefault();
juharr
+5  A: 

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();
Andrew Hare
+4  A: 

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

digEmAll
got it thanks, rod.
rod
+1  A: 

Just iterate over all elements of Dictionary (in this case only one)

foreach (KeyValuePair<v, k> keyValue in dictionary)
            {

            }
Michał Piaskowski