简体   繁体   中英

.NET - Whitelisting properties to anonymous object

I want to create an anonymous object dynamically based on an existing object and a whitelist.

For example I have the following class:

class Person
{
    string FirstName;
    string LastName;
    int Age;
}

Now I have created a function FilterObject to create a new anonymous obj based on the whitelist parameter like this:

public static class Filter
{
    public static object FilterObject(Person input, string[] whitelist)
    {
        var obj = new {};

        foreach (string propName in whitelist)
            if (input.GetType().GetProperty(propName) != null)
                // Pseudo-code:
                obj.[propName] = input.[propName];

        return obj;
    }
}

// Create the object:
var newObj = Filter.FilterObject(
    new Person("John", "Smith", 25), 
    new[] {"FirstName", "Age"});

The result should be like below. I want to use this object for my web API.

var newObj = new
{
    FirstName = "John",
    Age = 25
};

Is there any way to achieve this?

You can try with ExpandoObject (.net 4 or superior):

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

static class Filter
{
    public static object FilterObject(Person input, string[] whitelist)
    {
        var o = new ExpandoObject();
        var x = o as IDictionary<string, object>;

        foreach (string propName in whitelist)
        {
            var prop = input.GetType().GetProperty(propName);

            if (prop != null)
            {
                x[propName] = prop.GetValue(input, null);
            }
        }

        return o;
    }
}

This is only a sample based on your code, but it's a good starting point.

What about using a Dictionary?

public static object FilterObject(Person input, string[] whitelist)
{
    var obj = new Dictionary<string, object>();

    foreach (string propName in whitelist)
    {
        var prop = input.GetType().GetProperty(propName);

        if(prop != null)
        {
            obj.Add(propName, prop.GetValue(input, null));
        }
    }               

    return obj;
}

Another thing, do you really need to return an object? Because if you are always checking for properties in the whitelist that exists in the Person type, why just not return an instance of the Person class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM