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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}."); | |
} | |
} | |
} |