1

It is possible to override the TryGetIndex method of a dynamic object to access the dynamic object properties by index however I am dealing with an Expandoobject (of the System.dynamic namespace) which you can't inherit from. Is there a way around this? Thanks

Nic
  • 61
  • 8

1 Answers1

2

ExpandoObject is nothing but a fancy IDictionary which leverages the DLR.

There is no way you can access a IDictionary<TKey,TValue> via index. You may find ElementAt method of linq useful, but it is not. There is no ordering in dictionary, You can read more about hashtable datastructure(Dictionary is also a hashtable).

For accessing dictionary via index you may use OrderedDictionary. One disadvantage is that is is not generic.

Know more about issues when accessing elements via index from a Dictionary

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • You'll find how to get a generic OrderedDictionary here : http://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary/6374306 – Guillaume Aug 07 '14 at 09:40
  • An alternative to the archaic `OrderedDictionary` may in some uses be the `SortedList` class. You can say `var fortySecondValue = mySortedList.Values[42];` and similarly for `.Keys`. However, a `System.Dynamic.ExpandoObject` does not work as a `SortedList<,>`. – Jeppe Stig Nielsen Aug 07 '14 at 09:41
  • Clarification: `mySortedList.Values[42]` gives the value that is 42nd with respect to the sorting by keys that the `SortedList<,>` keeps. If you want the 42nd one with respect to the order in which the members were added to the collection, `SortedList<,>` is no good. ***So my comment above could be misleading!*** One can use `List>` or `List>` which is indexed by `int` after order of addition to the collection. – Jeppe Stig Nielsen Aug 07 '14 at 09:50