Question

I know there are many questions asked on this topic here on Stack Overflow, but I couldn't find any concrete answer to my current situation.

  1. I have a dynamically generated collection of rows.
  2. The property names (the columns, and the number of columns) are only known at run time.
  3. I have the following code,

    // collection gets populated at run time, the type T is dynamic.
    public void GenerateExcel<T>(string filename, IEnumerable<T> collection)
    {
        // Since the T passed is dynamic Type I am facing issues in getting
        // the property names.
        var type = typeof(T); // the type T is an anonymous type, and thus
                              // the 'type' variable is always an Object type.
        var columns = type.GetProperties().Length; // when I run this line it
                                                   // is obvious the properties 
                                                   // returned is always 0 so how
                                                   // do I get the properties?
    
        /* Implementation omitted */
    }
    
  4. I am calling the above method with the code below,

    GenerateExcel<dynamic>(
        "filename.xls",
        new[] { 
            new { Obj1 = "a", Obj2 = 1, Obj3 = 3.1, Obj4 = new DateTime(2014, 1, 1) }, 
            new { Obj1 = "b", Obj2 = 2, Obj3 = 3.2, Obj4 = new DateTime(2014, 1, 2) },
            new { Obj1 = "c", Obj2 = 3, Obj3 = 3.3, Obj4 = new DateTime(2014, 1, 3) },
            new { Obj1 = "d", Obj2 = 4, Obj3 = 3.4, Obj4 = new DateTime(2014, 1, 4) },
        } // these objects (Obj1, Obj2 ... (columns) are generated dynamically at run time).
    );
    

The same question was asked multiple times, here at Stack Overflow, but the solution is only when you have known property names, for example

  1. Get property value from C# dynamic object by string (reflection?)
  2. How to access property of anonymous type in C#? // property can be accessed only when the property name is known in advance.

Any help is greatly appreciated!

Was it helpful?

Solution

Get the first item, cast it to object, and then you can get the properties:

object e = collection.FirstOrDefault();
var columns = e.GetType().GetProperties().Length;

Or just:

collection.FirstOrDefault().GetType().GetProperties().Length;

OTHER TIPS

Can you use this?

 dynamic dy = obj;
 Console.WriteLine(dy.param);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top