title: iterate through string and count occurrences
body: <p>This is the question:</p>
  
  <ul>
  <li>Write a program that reads a string from the console and prints in alphabetical order all letters from the input string and how many times each one of them occurs in the string. </li>
  </ul>
  
  <p>It seemed interesting and not too complicated at first, but I couldn't solve it.</p>
  
  <pre><code>public static void Letters()
  {
          string input;
          Console.Write("Enter a string:  ");
          input = Console.ReadLine();
  
          var chars = new List&lt;char&gt;();
  
          //To populate characters with the letters of the input but without repetition
          for(int index = 0; index &lt; input.Length; index++)
          {
              if(!characters.Contains(input[index]))
                  characters.Add(input[index]);
          }
  
          //To increment the counter corresponding to the character index
          int[] counter = new int[characters.Count];
  
  
          //Now what ?!
  
      }
  </code></pre>
  
  <p>My thinking is:</p>
  
  <p>I create a collection to hold the letters of the input string, without any repetition.</p>
  
  <p>Then I use an int array of the same size such that each int holds the number of times the corresponding letter has occurred in the input string.</p>
  
  <p>I not only don't know how to implement this, but I have a feeling its not an ideal solution
  to the problem. There's probably a query or a lambda expression that should make this easy
  to implement and read.</p>
  
  <p>Note: The question following this is of the same nature. The difference is that it asks 
  to replace the repeated letters with a single one "aaabbbccc" to "abc". </p>
  
  <p>I will appreciate if the logic is described. I will try to implement it on my own,
  just point me to the logic. </p>
  
  <p>EDIT: </p>
  
  <p>This my answer using a dictionary </p>
  
  <pre><code>public static void Letters()
  {
          string input;
          Console.Write("Enter a string:  ");
          input = Console.ReadLine();
  
          var dict = new Dictionary&lt;char, int&gt;();
  
          for(int index = 0; index &lt; input.Length; index++)
          {
              char theKey = input[index]; //just for clarity
  
              if(!dict.ContainsKey(theKey))
                  dict.Add(theKey, 1);
              else
                  dict[input[index]]++;
          }
  
          foreach(var key in dict.Keys)
          {
              Console.WriteLine("{0}\t{1}", key, dict[key]);
          }
  </code></pre>