Dictionary with a single element

In case it Dictionary<object, object>

myDictionary

contains one element, what is the best way to get the value object (if I don't need the key)?

if (myDictionary.Count == 1)
{
    // Doesn't work
    object obj = myDictionary.Values[0];
}

      

thanks

+2


a source to share


5 answers


Depending on whether you want it to fail, if there are multiple objects or not, you can use

myDictionary.Value.Single();//Will fail if there more than one

      



or

myDictionary.Value.First();//Will just return the first regardless of the count

      

+8


a source


object obj = myDictionary.Values.Single();

      



+3


a source


I would never code the assumption that there will be only one. If you know there will always be exactly one, then why use a dictionary?

+3


a source


You cannot get the value directly or by index, you either need to know the key:

object obj = yourDictionary[theKeyThatYouHappenToKnow];

      

or use a counter:

var en = yourDictionary.GetEnumerator();
en.MoveNext();
object obj = en.Current.Value;
en.Dispose();

      

If you are using the 3.5 framework you can also use an extension method like Single

or First

to use the counter for you.

+1


a source


I think you can use an iterator.

myDictionary.GetEnumerator().Current

0


a source







All Articles