-
-
Save kgashok/60c5bbcd0e6bce82046cfeea716ed710 to your computer and use it in GitHub Desktop.
Why I started to feel differently about C# | Using Dictionaries
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
// | |
// (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