I am initializing dynamic with ExpandoObject and adding some items to it.
dynamic dy = new System.Dynamic.ExpandoObject();
dy.Property2 = new List<string>();
dy.Property2.Add("Two");
dy.Property2.Insert(0, "Zero");
var coll1 = (List<string>)dy.Property2;
var element = coll1.ElementAt(0);
above code works fine. but exception is thrown if replace last two statement with code mention below
var data = dy.Property2.ElementAt(0);
exception is 'System.Collections.Generic.List' does not contain a definition for 'ElementAt'
And it's absolutely right - List<T>
doesn't have an ElementAt
method. It only works in your original code because it's an extension method on IEnumerable<T>
. Dynamic typing doesn't let you call extension methods using the "special" syntax - but you can call it as a normal static method call:
var data = Enumerable.ElementAt(dy.Property2, 0);