.Net, C#, Generics

foreach with Generic Dictionary

I decided to write this post because few people approached me with the question:  “Is there a way to use foreach iteration statement with Dictionary<TKey, TValue> object?”

The quick response is: “Yes, use KeyValuePair.”

However, it wasn’t enough and I had to show an example.

Before I will show an example here, I want to remind you that Dictionary<TKey, TValue> class implements IDictionary<TKey, TValue> interface that extends ICollection<KeyValuePair<TKey, TValue> which in it turn is derived Dictionary Object from IEnumerable<KeyValuePair<TKey, TValue>.  As we know every class that implements IEnumerable interface must implement the GetEnumerator method.  And that is the reason why we can use foreach iteration statement.

Here’s the promised example.

   1: // Create a Dictionary object and load it with values.
   2: Dictionary<string, double> employeesWage = new Dictionary<string, double>();
   3: employeesWage.Add("Tom", 20000);
   4: employeesWage.Add("John", 15200);
   5: employeesWage.Add("Chris", 35000);
   6: employeesWage.Add("Brian", 38000);
   8: // Enumerate and display
   9: foreach (KeyValuePair<string, double> pair in employeesWage)
  10:   Console.WriteLine("{0} makes {1:C}", pair.Key, pair.Value);
.Net, C#, Coding, Generics, XML

GetAttribute Generics way.

As developers we often need to work with Xml.  In my case I found myself writing code like this one:
   1: public void Main()
   2: {
   3:   string name;
   4:   bool required;
   5:   XmlDocument _xmlDoc = new XmlDocument();
   6:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   7:   if (_xmlDoc.DocumentElement.HasAttribute("name"))
   8:     name = _xmlDoc.DocumentElement.GetAttribute("name");
   9:   if (_xmlDoc.DocumentElement.HasAttribute("required"))
  10:     required = Convert.ToBoolean(_xmlDoc.DocumentElement.GetAttribute("required"));
  11: }
I hated the fact that I have to for every attribute use two lines in my Main function.  Below you can see refactored code.
Note: You will need to pass XmlNamespaceManager if you’re using namespaces.
   1: public void Main()
   2: {
   3:   XmlDocument _xmlDoc = new XmlDocument();
   4:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   5:   string name = GetAttribute<string>(_xmlDoc.DocumentElement, "name");
   6:   bool required = GetAttribute<bool>(_xmlDoc.DocumentElement, "required");
   7: }
   1: private T GetAttribute<T>(XmlElement columnElement, string attributeName)
   2:   where T : IConvertible
   3: {
   4:   if (columnElement.HasAttribute(attributeName))
   5:     return (T) Convert.ChangeType(columnElement.GetAttribute(attributeName), typeof (T));
   6:   return default(T);
   7: }
I hope you’ll find it useful.

kick it on DotNetKicks.com