简体   繁体   中英

Create c# dynamic object from elements of a list

how to convert : A List :

var list = new List<string>(){"str1","str2"}

to a anonymous object :

var anonymousObject = new {str1 = "str1",str2 = "str2"}

during runtime

You can use the ExpandoObject which will give you the feature of dynamic type.

        var list = new List<string>() { "str1", "str2" };
        ExpandoObject obj = new ExpandoObject();
        var store = (IDictionary<string, object>)obj;

        list.ForEach(x => store.Add(x, x));

        dynamic lst  = obj;
        var val = lst.str1; // Test

You can also use extension method represented below (from here ).

Because converting list to dynamic object by iterating on items manually can be painful when there is many situations like this in your application.

You can use this extension method like this:

  dynamic list = new List<string>() { "str1", "str2" }
       .ToDictionary(dd => dd, dd => (object)dd)
       .ToExpando();

The extension method:

    public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary)
    {
        var expando = new ExpandoObject();
        var expandoDic = (IDictionary<string, object>)expando;

        // go through the items in the dictionary and copy over the key value pairs)
        foreach (var kvp in dictionary)
        {
            // if the value can also be turned into an ExpandoObject, then do it!
            if (kvp.Value is IDictionary<string, object>)
            {
                var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando();
                expandoDic.Add(kvp.Key, expandoValue);
            }
            else if (kvp.Value is ICollection)
            {
                // iterate through the collection and convert any strin-object dictionaries
                // along the way into expando objects
                var itemList = new List<object>();
                foreach (var item in (ICollection)kvp.Value)
                {
                    if (item is IDictionary<string, object>)
                    {
                        var expandoItem = ((IDictionary<string, object>)item).ToExpando();
                        itemList.Add(expandoItem);
                    }
                    else
                    {
                        itemList.Add(item);
                    }
                }

                expandoDic.Add(kvp.Key, itemList);
            }
            else
            {
                expandoDic.Add(kvp);
            }
        }

        return expando;
    }

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