Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small Adjustment on your Dynamic Approach #1

Closed
mikependon opened this issue May 4, 2019 · 0 comments

Comments

Projects
None yet
1 participant
@mikependon
Copy link

commented May 4, 2019

Codes taken from here: https://ozguradem.net/english/notes/2017/05/08/list-dynamic-to-list-dictionary/

Just to help you with your reflection, kindly change the following.

    public static Dictionary< string, dynamic> DynamicToDictionaryConverter(dynamic item)
    {
        if (IsDictionary(item))
        {
            return (Dictionary< string, dynamic>)item;
        }            
        
        Dictionary< string, dynamic> newItem = new Dictionary< string, dynamic>();
        PropertyInfo[] props = item.GetType().GetProperties();
        foreach (PropertyInfo prop in props)
        {
            newItem[prop.Name] = item.GetType().GetProperty(prop.Name).GetValue(item, null);
        }
        return newItem;
    }

to:

    public static Dictionary< string, dynamic> DynamicToDictionaryConverter(dynamic item)
    {
        if (IsDictionary(item)) -- why not simplify (if (item is Dictionary<string, dynamic>))??
        {
            return (Dictionary< string, dynamic>)item;
        }            
        
        var newItem = new Dictionary< string, dynamic>();
        var props = item.GetType().GetProperties();
        foreach (var prop in props)
        {
            newItem.Add(prop.Name, prop.GetValue(item, null)); // No need to call back the 'GetType()' here -- performance || Also, Add is much faster
        }
        return newItem;
    }

Lastly, I would suggest to do not use a reflection on this way. Have a way playing around with compiled expressions that manipulate the object Expression.Property method.

That would gladly help the performance.

@ozziest ozziest closed this in 70f8f3f May 8, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.