title: C# Converting a list<model> to a dictionary<enum, List<model>> based on enum property in the models?
body: <p>Not to be confused with: <a href="https://stackoverflow.com/questions/166174/how-can-i-convert-listobject-to-hashtable-in-c">How can I convert List to Hashtable in C#?</a> </p>
  
  <p>I have a list of Models that I want to organize into a hashtable with the enums as the key, and the list of Models (that have the enum's value) as the value.</p>
  
  <pre><code>public enum MyEnum
  {
      Blue,
      Green
  }
  
  public class MyModel
  {
      public MyModel(MyEnum myEnum, string foo, int bar)
      {
          this.MyEnum = myEnum;
          this.Foo = foo;
          this.Bar = bar;
      }
  
      public MyEnum MyEnum { get; set; }
      public string Foo { get; set; }
      public int Bar { get; set; }
  }
  
  List&lt;MyModel&gt; models = new List&lt;MyModel&gt;();
  
  models.Add(new MyModel(MyEnum.Blue, "How", 1));
  models.Add(new MyModel(MyEnum.Green, "Now", 2));
  models.Add(new MyModel(MyEnum.Blue, "Brown", 3));
  models.Add(new MyModel(MyEnum.Green, "Cow", 4));
  </code></pre>
  
  <p>What is the easiest way to convert the list into a hash table that would look like this (Forgive the json):</p>
  
  <pre><code>{ 
     Blue:
     [
        { Blue, "How", 1 },
        { Blue, "Brown", 3 }
     ],
     Green:
     [
        { Green, "Now", 2 },
        { Green, "Cow", 4 }
     ]
  }
  </code></pre>
  
  <p>When I do something like this:</p>
  
  <pre><code>var taskTable = tasks.Cast&lt;TaskModel&gt;().ToDictionary(o =&gt; o.Task); (Where Task is the Enum)
  </code></pre>
  
  <p>I get this exception: "An item with the same key has already been added."</p>
  
  <p>One liners with Lambda or Linq are appreciated!</p>