Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with single item

Tags:

c#

dictionary

In the case where Dictionary<object, object> myDictionary happens to contain a single item, what is the best way to retrieve the value object (if I don't care about the key) ?

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

Thanks

like image 473
alhazen Avatar asked Jan 19 '26 15:01

alhazen


1 Answers

Depending on whether you want it to fail if there's multiple object or not you can use either

myDictionary.Values.Single(); // Will fail if there's more than one

or

myDictionary.Values.First(); // Will just return the first regardless of the count
like image 179
Rune FS Avatar answered Jan 22 '26 15:01

Rune FS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!