title: How to use Linq and lambda expressions on a Dictionary<string, List<T>> to a specify its order based on Key
body: <p>So I have a Dictionary with string keys, and the value is a List of objects.  Each object in each List has a property value which is equal to that List's associated key.  In other words, the Dictionary is grouping objects by property value via the key.  For example, let's say we have,</p>
  
  <pre><code>Dictionary&lt;string, List&lt;Animal&gt;&gt; GroupedByClass = new Dictionary&lt;string, Animal&gt;();
  </code></pre>
  
  <p>Where Animal is an object which contains a string property named "ClassType" which has valid options of "Mammal", "Reptile", or "Amphibian", etc. </p>
  
  <p>The Animal class could also have string property named "Species" which more uniquely defines each object in the Dictionary.</p>
  
  <p>A pseudocode description of the contents of the Dictionary could be:</p>
  
  <pre><code>&lt;"Mammal", List&lt;Animal&gt;&gt; 
  </code></pre>
  
  <p>where the Animals in the list have Species "Dog", "Cat"
      &lt;"Reptile", List>
  where the Animals in the list have Species "Snake", "Lizard", and "Turtle"
      &lt;"Amphibian", List>
  where the Animals in the list have Species "Salamander" and "Frog"</p>
  
  <p>I want to rearrange this Dictionary by the key value such that the values with a key of "Reptile" are first, then "Amphibian", and then finally "Mammal".  Note that I do not want to sort this based on alphabetical order, I want to specify my own order.</p>
  
  <p>I know I could solve this problem by simply iterating through the Dictionary a few times, extracting only the items with the right key.  For example, I could do it like this,</p>
  
  <pre><code>Dictionary&lt;string, List&lt;Animal&gt;&gt; temp = new Dictionary&lt;string, List&lt;Animal&gt;&gt;();
  
  foreach(KeyValuePair&lt;string, List&lt;Animal&gt;&gt; item in GroupedByClass)
  {
      if(item.Key == "Reptile")
      {
          temp.Add(item.Key, item.Value);
      }
  }
  
  foreach(KeyValuePair&lt;string, List&lt;Animal&gt;&gt; item in GroupedByClass)
  {
      if(item.Key == "Amphibian")
      {
          temp.Add(item.Key, item.Value);
      }
  }
  
  foreach(KeyValuePair&lt;string, List&lt;Animal&gt;&gt; item in GroupedByClass)
  {
      if(item.Key == "Mammal")
      {
          temp.Add(item.Key, item.Value);
      }
  }
  
  return temp;
  </code></pre>
  
  <p>However, this seems inelegant, and I was wondering if there was a better answer for this problem using Linq queries and lambda expressions. </p>