Dynamically read properties from c# expando object

s.k.paul picture s.k.paul · Jan 21, 2017 · Viewed 10.3k times · Source

Currently I have the following method-

public void CreateWorkbook<T>(List<T> ItemList)
{
     PropertyInfo[] properties= typeof(T).GetProperties();
     foreach (PropertyInfo prop in properties)
     {
     }
}

I would like to replace T with expando object. But I can't read properties from an expando object.

is there any way to do it?

Answer

Ivaylo Stoev picture Ivaylo Stoev · Jan 21, 2017

You can get the properties by using something like:

public static void CreateWorkbook(List<ExpandoObject> ItemList)
        {
            foreach(var item in ItemList)
            {
                IDictionary<string, object> propertyValues = item;

                foreach (var property in propertyValues.Keys)
                {
                    Console.WriteLine(String.Format("{0} : {1}", property, propertyValues[property]));
                } 
            }
        }