How to Find Item in Dictionary Collection?

后端 未结 4 838
星月不相逢
星月不相逢 2020-12-28 13:16

I have declared and populated the following collection.

protected static Dictionary _tags;

Now I want to look locate

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 14:05

    thisTag = _tags.FirstOrDefault(t => t.Key == tag);
    

    is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

    The basic solution would be:

    if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
    

    But that requires 2 lookups.

    TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

    string myValue;
    if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }
    

    VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

    if (_tags.TryGetValue(tag, out string myValue))
    {
        // use myValue;
    }
    // use myValue, still in scope, null if not found
    

提交回复
热议问题