1

I am assigning property names of a dynamic object as ints in string form. The int value represents an int ID in a database I am using. However I am stuck on how to retrieve the value assigned to the property as shown below:

dynamic test = new ExpandoObject()
IDictionary<string, object> proxyFiler = test as IDictionary<string, object>;
proxyFiler["four"] = 4;
proxyFiler["5"] = 5;
int r = test.four; // Works
int s = test.5; // Doesn't work

A method which reads the database will return an "int" and I would like to be able to access the property value with that property name.

To expand on this: what if I wanted to do a linq query to sort out a list of dynamic objects according to a property name? In this case I need to get the propertyName which I have retrieved as a string e.g. "15":

 return disorderedList.OrderBy(o => o.propertyName).ToList();

Does anyone know a simple solution to this problem or do you recommend a different approach? Thanks.

Nic
  • 61
  • 8

1 Answers1

4

In order for dynamic to work in this way, the key has to follow the rules for valid identifier names in C# (the rules are specified in this outdated MSDN page, but also in the C# language specification). A single number (5) is not an allowed identifier name, which is why that doesn't work.

Note that you can still retrieve the value by using the type as a dictionary, in a similar manner to how you populated it.

As for your second example - you are never using value, so it has no effect. It's the same as just writing int r = test.four;


Edit:

I believe, given your approach, you'd need to cast to a dictionary:

return disorderedList
          .OrderBy(o => ((IDictionary<string, object>)o)[propertyName]).ToList();
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks Reed, do you think there is a way around the problem? I've edited the question to explain my problem better. – Nic Aug 06 '14 at 17:59
  • @Nic Just access it as a dictionary - the same way you store it – Reed Copsey Aug 06 '14 at 18:03
  • Thanks again @ReedCopsey. I have now expanded the question. – Nic Aug 06 '14 at 18:20
  • @Nic I believe what I posted will do what you want. – Reed Copsey Aug 06 '14 at 18:37
  • Actually @ReedCopsey, when trying to do what you suggested I get this error: "Additional information: Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject'" – Nic Aug 06 '14 at 18:54
  • @Nic I had a typo at one point - make sure to try the latest, since it should work (the cast happens before the indexer) – Reed Copsey Aug 06 '14 at 18:57
  • For simplicity, if I need to access the value of the property for multiple (identical in properties) dynamic objects maybe it would be a good idea to access the dynamic object properties by index. What do you guys think? @ReedCopsey – Nic Aug 07 '14 at 07:56