0

If I have a list such as :

var ListCommandQuery = new List<dynamic> { }; 

ListCommandQuery.Add( 
new { User_ID = "4", User_Name = "jhony" ,    Mobile_Phone = 054175548999} );

and i want to print only the Properties key names not the values
so the result will show me :

User_ID 
User_Name 
Mobile_Phone 

instead of :

4
jhony
054175548999

How that can be done ?

The Doctor
  • 636
  • 1
  • 7
  • 23
  • 2
    You need to use reflection – Sparrow Feb 19 '17 at 21:08
  • 1
    The lazy in me says, reference JSON.NET and use the built-in ability therein, to cast a `dynamic` into a `JObject`. A `JObject`, of course, will nicely give you a `Dictionary` interface to all the field names via the `.ToObject` method. – code4life Feb 19 '17 at 21:15
  • See http://stackoverflow.com/questions/2634858/how-do-i-reflect-over-the-members-of-dynamic-object. – Peter Bons Feb 19 '17 at 21:16
  • @code4life ,@Peter Bons : Thank you guys for suggestions and explanations :) and the solution that works for me is the one posted by "Filip Cordas" down here : http://stackoverflow.com/questions/42332870/get-key-names-from-a-list/42332977#42332977 – The Doctor Feb 19 '17 at 21:35

1 Answers1

3

When using anonymous types you need the type definition

foreach (var item in listCommandQuery)
{
     foreach (var prop in item.GetType().GetProperties())
     {
              Console.WriteLine(prop.Name);
     }
}

In an anonymous object the names are not keys like in a DynamicObject but actual Properties. The Compiler creates an actual class for you in the background. Unlike ExpandoObject where the object is an IDictonery

The Doctor
  • 636
  • 1
  • 7
  • 23
Filip Cordas
  • 2,531
  • 1
  • 12
  • 23
  • thank you very much , it works perfect and short codes are always my favor . and the description was good to understand the reasons behind , thumb up for you :) – The Doctor Feb 19 '17 at 21:33