title: Dynamically create anonymous object from list values c#
body: <p>I have a list (or can be array) of strings that I want to dynamically create an anonymous object from. How do I do this?</p>
  
  <pre><code>var dataSet = new DataSet();
  dataSet.ReadXml(@"");
  var dataTable = dataSet.Tables[0];
  var dataRow = dataTable.Rows[0];    
  
  var keys = new List&lt;string&gt; {"Column1","Column2"};
  var result = new {keys[0] = dataRow[keys[0]], keys[1] = dataRow[keys[1]]}
  </code></pre>
  
  <p>So that list named "keys" is going to be created outside this method and can contain 1 to many values. I tried creating a dictionary and looping through the list and adding key/value pairs to the dictionary but then I couldnt figure out how to convert the dictionary back to an anonymous type. I also experimented with the expando objects but that didn't seem to get me any farther.</p>
  
  <p>I must be able to return an anonymous type as the result of this method will be using with the GroupBy clause of a LINQ query.</p>
  
  <p>Here is the method I had to dynamically  create the dictionary:</p>
  
  <pre><code>    public object Key(DataRow dataRow, List&lt;String&gt; keys)
      {
          var dictionary = new IDictionary&lt;string, object&gt;;
          foreach (string key in keys)
          {
              dictionary.Add(key, dataRow[key]);
          }
          return dictionary;
      }
  </code></pre>
  
  <p>Here is my LINQ query:</p>
  
  <pre><code>var duplicates = dataTable.AsEnumerable().GroupBy(r =&gt; Key(r, keys)).Where(c =&gt; c.Count() &gt; 1).ToList();
  </code></pre>
  
  <p>The GroupBy clause works if I hardcode in an anonymous type from the Key() method. Basically I just need the GroupBy clause to be dynamically set based upon the values in the keys list.</p>