How to convert object to Dictionary in C#?

前端 未结 15 1692
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 17:58

How do I convert a dynamic object to a Dictionary in C# What can I do?

public static void MyMethod(object obj)
{
    if (typ         


        
相关标签:
15条回答
  • 2020-12-13 18:25
    object parsedData = se.Deserialize(reader);
    System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable;
    

    then will be able to enumerate it!

    0 讨论(0)
  • 2020-12-13 18:28

    I use this simple method:

    public Dictionary<string, string> objToDict(XYZ.ObjectCollection objs) {
        var dict = new Dictionary<string, string>();
        foreach (KeyValuePair<string, string> each in objs){
            dict.Add(each.Key, each.Value);
        }
        return dict;
    }
    
    0 讨论(0)
  • 2020-12-13 18:29

    I use this helper:

    public static class ObjectToDictionaryHelper
    {
        public static IDictionary<string, object> ToDictionary(this object source)
        {
            return source.ToDictionary<object>();
        }
    
        public static IDictionary<string, T> ToDictionary<T>(this object source)
        {
            if (source == null)
                ThrowExceptionWhenSourceArgumentIsNull();
    
            var dictionary = new Dictionary<string, T>();
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
                AddPropertyToDictionary<T>(property, source, dictionary);
            return dictionary;
        }
    
        private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
        {
            object value = property.GetValue(source);
            if (IsOfType<T>(value))
                dictionary.Add(property.Name, (T)value);
        }
    
        private static bool IsOfType<T>(object value)
        {
            return value is T;
        }
    
        private static void ThrowExceptionWhenSourceArgumentIsNull()
        {
            throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
        }
    }
    

    the usage is just to call .ToDictionary() on an object

    Hope it helps.

    0 讨论(0)
提交回复
热议问题