开发者

Dictionary with single item

开发者 https://www.devze.com 2022-12-28 17:23 出处:网络
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) ?

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.Coun开发者_StackOverflow中文版t == 1)
{
    // Doesn't work
    object obj = myDictionary.Values[0];
}

Thanks


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

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

or

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


object obj = myDictionary.Values.Single();


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


You can't get the value directly or by index, you have to either know the key:

object obj = yourDictionary[theKeyThatYouHappenToKnow];

or use an enumerator:

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

If you are using framework 3.5, you can also some extension method like Single or First to use the enumerator for you.


I think you can use an iterator.

myDictionary.GetEnumerator().Current

0

精彩评论

暂无评论...
验证码 换一张
取 消