Get ANY value in a Dictionary C#

时间:2018-02-05 12:56:59

标签: c# dictionary

How can I get a value (no value in particular, just any value) in a C# Dictionary without any key? I mean something that just returns ANY value contained in the collection.

I know of the existence of Linq First(), but I don't know exactly how expensive that is, and I am developing a game, so performance is a concern for me. That said, the operation is not done every frame, so it's kind of fine, but is there a more efficient method aside from First()?

3 个答案:

答案 0 :(得分:5)

First() will use LINQ, which builds on IEnumerable<T>. Now; Dictionary<TKey, TValue> has a custom value-type enumerator, so using LINQ will cause boxing of the enumerator (LINQ isn't very good at using custom enumerators). A slightly more frugal approach may be to simply do something like:

foreach(var pair in dictionary) return pair.Value;
return default; // if empty

Which is broadly equivalent to:

using (var iter = a.GetEnumerator()) {
    return iter.MoveNext() ? iter.Current.Value : default;
}

Note that this won't be random in any way - nor will it predictably sorted. Probably not great properties for a game.

答案 1 :(得分:1)

Dictionary<TKey, TValue>还有Values类型的成员IEnumerable<TValue>Keys类型的IEnumerable<TKey>。这意味着您可以执行dict.Values.First()来获取值。但这可能不是最高效的选择。

答案 2 :(得分:0)

Access by key is always faster than linq operations:

var contents = myDictionary[key];