It can be tedious to iterate over a generic Dictionary in C#, especially if the Dictionary contains complex types. The values you’re interested in are properties of the iteration variable. I never know what to name the iteration variable (here I name it “pair”), which is an indicator this code is clumsy.

private void IterateOverDictionary()
{
Dictionary<string, HashSet<string>> claims = GetClaims();
foreach (KeyValuePair<string, HashSet<string>> pair in claims)
{
string claimType = pair.Key;
HashSet<string> claimValues = pair.Value;
foreach (string claimValue in claimValues)
{
Console.WriteLine($"{claimType} = {claimValue}.");
}
}
}

Make it easier on yourself by using C#’s Tuple Deconstruction language feature. First, write an extension method for the generic KeyValuePair class.

public static class ExtensionMethods
{
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> Tuple, out T1 Key, out T2 Value)
{
Key = Tuple.Key;
Value = Tuple.Value;
}
}

Or, instead of writing the extension method, you can add a reference to my ErikTheCoder.ServiceContract package and add a using ErikTheCoder.ServiceContract; statement.

Then rewrite your foreach loop with more a compact, yet readable, syntax.

private void IterateOverDictionaryUsingTupleDeconstruction()
{
Dictionary<string, HashSet<string>> claims = GetClaims();
foreach ((string claimType, HashSet<string> claimValues) in claims)
{
foreach (string claimValue in claimValues)
{
Console.WriteLine($"{claimType} = {claimValue}.");
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *