如何正确转换为List <expandoobject> </expandoobject>

时间:2013-05-08 10:41:04

标签: c# linq expandoobject

请查看以下代码

private static List<ExpandoObject> GetDBDetails()
        {
            var directoryPath = Environment.CurrentDirectory.Replace("\\bin\\Debug", "\\DataSource");
            var filePath = Path.Combine(directoryPath, "DBDetail.xml");
            try
            {
                //Load xml
                XDocument xdoc = XDocument.Load(filePath);
                if (xdoc == null) return null;


                List<ExpandoObject> dbDetails = (from dbDetail in xdoc.Descendants("database")
                                       select new ExpandoObject
                                            {
                                                DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value),
                                                DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value)
                                                                                                });
               return dbDetails;
            }
            catch (Exception ex)
            {
                McAfee.EnterpriseLibrary.Logging.LogUtil.LogEntry(ex, System.Diagnostics.TraceEventType.Critical);
                return null;
            }
        }

我收到错误

System.Dynamic.ExpandoObject'不包含'DBDetailId'的定义 System.Dynamic.ExpandoObject'不包含'DBServerId'的定义

如何纠正这个问题?

1 个答案:

答案 0 :(得分:4)

您需要将ExpandoObject转换为dynamic

 xdoc.Descendants("database")
            .Select(dbDetail =>
                        {
                            dynamic expandoObj = new ExpandoObject();
                            expandoObj.DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value);
                            expandoObj.DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value);
                            return (ExpandoObject) expandoObj;
                        })
            .ToList();

您也可以将ExpandoObject投射到IDictionary<string, object>

var x = new ExpandoObject() as IDictionary<string, object>;
x.Add("DBDetailId", Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value));
x.Add("DBServerId", Convert.ToInt32(dbDetail.Attribute("dbServerID").Value));