简体   繁体   English

根据列表元素创建C#动态对象

[英]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. 您可以使用ExpandoObject,它将为您提供动态类型的功能。

        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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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