Which mechanism is a better way to extend Dictionary to deal with missing keys and why?

后端 未结 3 1351
一整个雨季
一整个雨季 2021-01-04 00:48

There is a minor annoyance I find myself with a lot - I have a Dictionary that contains values that may or may not be there.

So norm

3条回答
  •  太阳男子
    2021-01-04 01:20

    I'm unable to infer from your question what should be done when a key is not found. I can imagine nothing should be done in that case, but I can also imagine the opposite. Anyway, an elegant alternative for a series of these TryGetValue-statements you describe, is using one of the following extension methods. I have provided two options, depending on whether something should be done or not when the dictionary does not contain the key:

    ///  Iterates over all values corresponding to the specified keys, 
    ///for which the key is found in the dictionary. 
    public static IEnumerable TryGetValues(this Dictionary dictionary, IEnumerable keys)
    {
        TValue value;
        foreach (TKey key in keys)
            if (dictionary.TryGetValue(key, out value))
                yield return value;
    }
    
    ///  Iterates over all values corresponding to the specified keys, 
    ///for which the key is found in the dictionary. A function can be specified to handle not finding a key. 
    public static IEnumerable TryGetValues(this Dictionary dictionary, IEnumerable keys, Action notFoundHandler)
    {
        TValue value;
        foreach (TKey key in keys)
            if (dictionary.TryGetValue(key, out value))
                yield return value;
            else
                notFoundHandler(key);                        
    }
    

    Example code on how to use this is:

    TKey[] keys = new TKey{...};
    foreach(TValue value in dictionary.TryGetValues(keys))
    {
        //some action on all values here
    }
    

提交回复
热议问题