DocSmiley
DocSmiley

Reputation: 123

Retrieving unknown column names from dynamic objects C#

I am being given a list of dynamic objects (the results of a SQL query). I can access any value of a specific element if I know the name of the column to access. However there are an unknown number of columns with unknown names.

How can I generate a list of the column names from the dynamic objects? I'm trying to avoid querying the DB again for information I should already have in this list. If I can get a list of strings with the column names of this table I should be able to access the data as I like.

Thanks in advance for any suggestions.

Upvotes: 0

Views: 847

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063629

dynamic can mean different things. What you need to look at is what the objects actually are. Likely options:

  • a regular type (perhaps generated on the fly) with properties / fields per column - in which case reflection will work
  • a meta-type provider which also implements a dictionary index (check for IDictionary<string,object> etc) - in which case cast as the dictionary and access the keys
  • a meta-type provider which does not provide a dictionary - in which case this is... problematic, but which can sometimes be done via the dynamic meta object api: http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicmetaobject.getdynamicmembernames.aspx

Upvotes: 3

Related Questions