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
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
}