Skip to content

Instantly share code, notes, and snippets.

@ahmedahamid
Last active May 10, 2016 02:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmedahamid/5d9a929d111940cdf2ae to your computer and use it in GitHub Desktop.
Save ahmedahamid/5d9a929d111940cdf2ae to your computer and use it in GitHub Desktop.
Why I started to feel differently about C# | Using Dictionaries
//
// (1) C#: Defining an initializing a dictionary [key type=string, value type=int]
//
Dictionary<string, int> dict = new Dictionary<string, int>()
{
{"Eve", 101},
{"George", 150},
{"Emma", 200}
};
//
// (2) C#: Searching for any key (string) - an *almost* O(1) operation
//
if (dict.ContainsKey("James"))
//
// (3) C#: Search for any value (int) - a linear operation
//
if (dict.ContainsValue(120))
//
// (4) C#: Iterating over keys of a dictionary
//
foreach (string key in dict.Keys)
//
// (5) C#: Iterating over values of a dictionary
//
foreach (int val in dict.Values)
//
// (6) C#: Iterating over key-value pairs of a dictionary
//
foreach (KeyValuePair<string, int> pair in dict)
{
Console.WriteLine(string.Format("{0} has value {1}", pair.Key, pair.Value));
}
// or better
foreach (var pair in dict)
//
// (7) C#: Adding a key with a corresponding value
//
dict["Janice"] = 300;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment