Search code examples
c#dictionaryunity-game-enginekeykey-value

Is there any way to check if a KeyValuePair<string, int> contains a specific Key in a Dictionary in one line?


In my code I have a Dictionary, which at first was just <string, int>. However, I needed a way for two things with the same string to be separate elements in the Dictionary, so I made the Key int and the Value a KeyValuePair<string, int>.

Dictionary<int, KeyValuePair<string, int>>()

The problem is, I need to check if a specific string exists in the Dictionary, preferably without the use of a for/foreach loop. Using Dictionary.ContainsValue I could check for a KeyValuePair, but the int in the KeyValuePair isn't specified and would need to be if I used ContainsValue.

Is there any way to check if the Dictionary contains a KeyValuePair with a specific Key in one line?

If anyone has any other fixes for the problem that'd be great too.

Thanks in advance!


Solution

  • +1 that Dictionary no longer looks like an adequate data structure for your needs. You have gone from needing a unique string (essentially indexed value) to a structure where the string can be duplicated. You could just as easily use a List<KeyValuePair<string,int>> now.

    However yes you can still check the values of the dictionary:

    // Does a string exist: 
    var exists = myDictionary.Values.Any(x => x.Key == myString);
    
    // Values with string: 
    var keyValues = myDictionary.Values.Where(x => x.Key == myString);
    

    Unless you still have code that indexes the dictionary by the unique ID then there is no point continuing to use a dictionary.