How to fetch data from List<dynamic>()? [duplicate]

风流意气都作罢 提交于 2019-12-20 07:07:05

问题


My code is like this

var eventDocs = new List<dynamic>();     
foreach (var node in eventtypeNode.GetDescendantNodes())
{
    string files = node.GetProperty("document").Value;
    eventDocs.Add(new { Id = node.Id, Name = node.Name, CreatedOn = node.CreateDate, Path = files });
}

This works good. Now I am trying to fetch the data out of this dynamic list

foreach (var eventDoc in eventDocs)
{
     eventDoc.----  //nothing comes on intellisence
}

Nothing comes on IntelliSense? Am I doing anything wrong?


回答1:


You won't get anything from Intellisense precisely because you've got a List<dynamic>. You're saying, "I don't know at compile-time what this list will contain. When I access members of the elements, just bind that dynamically at execution-time."

Given that you're deferring binding to execution time, why would you be surprised that Intellisense can't tell what will be in the list?

It looks to me like you should change your code to use a LINQ query to start with - then you can have a list with a known element type, which will be an anonymous type.

var eventDocs = eventtypeNode.GetDescendantsNodes()
      .Select(node => new { Id = node.Id, 
                            Name = node.Name, 
                            CreatedOn = node.CreateDate,
                            Path = node.GetProperty("document").Value })
      .ToList();



回答2:


Intellisense will not show suggestions, since the data is dynamic, and it doesn't know what to show.

But you know what it contains. So just code and you'll be fine.

Also, you don't need dynamic objects here. Since what you want is well-defined just define your class with necessary properties and methods and then create the list:

List<YourClass> list = new List<YourClass>();

And then Intellisense will become intelligent enough to show the suggestions ;)




回答3:


You cannot access dynamic members like this, try GetDynamicMemberNames() and GetMetaObject method



来源:https://stackoverflow.com/questions/23670408/how-to-fetch-data-from-listdynamic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!