Search code examples
c#jsondictionarykeyvaluepair

Usage of ContainsKey method with a variable


I have a string variable which holds some value and I want to be able to check if that string exists in a dictionary as a key with its variable name. For a clearer understanding as you can see in the following code;

        string searchDuration = "200";

        var response = new Dictionary<string, string>()
        {
            {"searchDuration","200"},
            {"minRssi", "-70"},
            {"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
            {"txPowerLevel","200"},
            {"peripheralId","123wrong"}
        };

I'm able to use ContainsKey method as following;

        if (response.ContainsKey("searchDuration"))
            if (searchDuration == pair.Value)
                isEqual = true;

But I don't(actually can't) use it this way because;

  • I need to pass in every string variable dynamically, I can't write every variable name as a string to pass in to ConstainsKey method
  • It only check values and there might be multiple values with "200", this situation gives me false results.
  • I want to compare the value "200" only with related key which is "searchDuration", not with "txPowerLevel" which has the same value.

Is there a way to check whether a string variable exists as a key in a dictionary to compare it's value with dictionary members?


Solution

  • I'd suggest this approach:

    string searchDuration = "200";
    
    var response = new Dictionary<string, string>()
    {
        {"searchDuration","200"},
        {"minRssi", "-70"},
        {"optionalFilter","NO_FILTERS_ACTIVE_SCANNING"},
        {"txPowerLevel","-16"},
        {"peripheralId","123wrong"}
    };
    
    var wasItThere = response.TryGetValue(nameof(searchDuration), out var value);
    Console.WriteLine(wasItThere && (value == searchDuration));
    

    TryGetValue is better than ContainsKey since it gets the value at the same time as checking whether the key is there.

    nameof is used to convert the variable name to its string representation.

    I have explicitly not used pair.Value since that code in your original question strongly implies you are iterating through the Dictionary. This is not a good idea (performance wise).