title: .NET - Whitelisting properties to anonymous object
body: <p>I want to create an anonymous object dynamically based on an existing object and a whitelist. </p>
  
  <p>For example I have the following class:</p>
  
  <pre><code>class Person
  {
      string FirstName;
      string LastName;
      int Age;
  }
  </code></pre>
  
  <p>Now I have created a function <code>FilterObject</code> to create a new anonymous <code>obj</code> based on the <code>whitelist</code> parameter like this:</p>
  
  <pre><code>public static class Filter
  {
      public static object FilterObject(Person input, string[] whitelist)
      {
          var obj = new {};
  
          foreach (string propName in whitelist)
              if (input.GetType().GetProperty(propName) != null)
                  // Pseudo-code:
                  obj.[propName] = input.[propName];
  
          return obj;
      }
  }
  
  // Create the object:
  var newObj = Filter.FilterObject(
      new Person("John", "Smith", 25), 
      new[] {"FirstName", "Age"});
  </code></pre>
  
  <p>The result should be like below. I want to use this object for my web API.</p>
  
  <pre><code>var newObj = new
  {
      FirstName = "John",
      Age = 25
  };
  </code></pre>
  
  <p>Is there any way to achieve this?</p>