0

I have this scenario where we use model classes to generate an excel file, however due to the new requests it requires to process Dynamic objects that includes the attributes which are necessary to be processed by the excel file code generator.

So if I have model, let's say User:

[Sheet]
public class User 
{
    [Column]
    public string FirstName { get; set; }

    [Column]
    public string LastName { get; set; }

    [Column]
    public string EmailAddress { get; set; }
}

So if a user does not want to include the EmailAddress field this should be excluded when export engine try to do model.GetType().GetProperties() to process the property name and its value to the excel.

I tried to use the ExpandoObject however it does not work when I try to access the properties through model.GetType().GetProperties() even if I have passed the whole PropertyInfo to the IDictionary<string, object> value.

How do I do this using dynamic? FYI the custom attribute is import to be included as part of the object and it's property because there is a filtering using these attribute to process even further the model class.

Update

This object is a generic IList, for instance it can be IList<User>since it's data export to excel.

rpmansion
  • 1,964
  • 1
  • 9
  • 26
  • See: https://stackoverflow.com/questions/2634858/how-do-i-reflect-over-the-members-of-dynamic-object – stephen.vakil Mar 18 '19 at 19:31
  • What do you mean "dynamic object"? The keyword `dynamic` does not signify a type; it's a directive to the compiler to treat the object a certain way. What is the actual type of the object? Is it an instance of the `User` class? – John Wu Mar 18 '19 at 23:33
  • @JohnWu The instance of the user type can be converted to dynamic (ExpandoObject) in which I can remove some properties to be included when export the user data – rpmansion Mar 18 '19 at 23:38

1 Answers1

0

I believe you are asking how to retrieve all the "properties" (the dynamic members) from an ExpandoObject. All you have to do is iterate over it.

public static void Main()
{
    dynamic d = new ExpandoObject();

    d.Foo = "Hello";

    Console.WriteLine("Should have one  property:");

    foreach (var i in d )
    {
        Console.WriteLine("Name: {0} Type: {1} Value: {2}", i.Key, i.Value.GetType().Name, i.Value);
    }

    Console.WriteLine("\r\nShould have two properties:");

    d.Bar = 123.45F;

    foreach (var i in d)
    {
        Console.WriteLine("Name: {0} Type: {1} Value: {2}", i.Key, i.Value.GetType().Name, i.Value);
    }
}

Output:

Should have one  property:
Name: Foo Type: String Value: Hello

Should have two properties:
Name: Foo Type: String Value: Hello
Name: Bar Type: Single Value: 123.45

See my example on DotNetFiddle.

John Wu
  • 50,556
  • 8
  • 44
  • 80