Skip to content

Instantly share code, notes, and snippets.

@kgashok
Forked from ahmedahamid/C#Example.cs
Created May 10, 2016 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgashok/60c5bbcd0e6bce82046cfeea716ed710 to your computer and use it in GitHub Desktop.
Save kgashok/60c5bbcd0e6bce82046cfeea716ed710 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