title: Attempting to obtain properties / fields from an (anonymous class) object linq is creating
body: <p>I'm having trouble figuring out what I'm doing wrong here.  I have some LINQ that returns an <code>IQuery</code> object, and later in the code, I'm attempting to list out the attributes returned.  This is best explained by this abbreviated code (the actual LINQ is a lot more complex and involves joins - the LINQ itself works fine):</p>
  
  <pre><code>public IQueryable&lt;Object&gt; FindAll()
  {
      var query = from user in _db.Users
      select new
      {
          id = user.Id,
          is_active = user.IsActive,
          email = user.Email,
          dob = user.Dob,
          user.user_type,
      };
      return query;
  }
  </code></pre>
  
  <p>Elsewhere in the code I have:</p>
  
  <pre><code>query.ConvertToCsv();
  </code></pre>
  
  <p>Although I have attempted to insert a <code>.ToList()</code> in that call as well.</p>
  
  <p>The <code>ConvertToCsv</code> has:</p>
  
  <pre><code>public static string ConvertToCSV&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)
  {
      StringBuilder sb = new StringBuilder();
  
      var properties = typeof(TSource).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
  
      var enumerable = source as IList&lt;TSource&gt; ?? source.ToList();
      if (!enumerable.Any()) return "";
  
      string headerString = "";
  
      foreach (var prop in properties)
      {
          headerString += (headerString.Length &gt; 0 ? "," : "") + prop.Name;
      }
      sb.AppendLine(headerString);
  
      foreach (TSource item in enumerable)
      {
          string line = string.Join(",", properties.Select(p =&gt; p.GetValue(item).ToCsvValue()).ToArray());
          sb.AppendLine(line);
      }
  
      return sb.ToString();
  }
  </code></pre>
  
  <p>Note I have also tried to pull out the property names with this code:</p>
  
  <pre><code>PropertyInfo[] pi = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  var properties = pi.OrderBy(x =&gt; x.MetadataToken);
  foreach (PropertyInfo p in properties)
  { etc etc }
  </code></pre>
  
  <p>In all cases, the property or field list returns an empty list, and as such, I can't iterate through the object to spit out a header row or data rows. Tracing through all the code and inspecting the variables indicates that everything is fine until I get to the <code>GetProperties</code>/<code>GetFields</code> line and the code fails. </p>
  
  <p>What rookie mistake am I making?  Should I be replacing <code>&lt;Object&gt;</code> with something else?</p>