Get all keys in Dictionary containing value x

后端 未结 2 1285
花落未央
花落未央 2021-02-12 22:38

I have this:

Dictionary dict = new Dictionary();

I want to select all the items in the dictionary

相关标签:
2条回答
  • 2021-02-12 23:19

    Built-in function? No sorry... but another (not so beautiful) way is to iterate using foreach(KeyValuePair<integer, string> ...

    0 讨论(0)
  • 2021-02-12 23:24

    Well it's reasonably simple with LINQ:

    var matches = dict.Where(pair => pair.Value == "abc")
                      .Select(pair => pair.Key);
    

    Note that this won't be even slightly efficient - it's an O(N) operation, as it needs to check every entry.

    If you need to do this frequently, you may want to consider using another data structure - Dictionary<,> is specifically designed for fast lookups by key.

    0 讨论(0)
提交回复
热议问题