How to convert object to Dictionary in C#?

前端 未结 15 1697
隐瞒了意图╮
隐瞒了意图╮ 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:10

    You can create a generic extension method and then use it on the object like:

    public static class Extensions
    {
        public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
        {
            // if obj is null throws exception
            Contract.Requires(obj != null);
    
            // gets the type of the obj parameter
            var type = obj.GetType();
            // checks if obj is of type KeyValuePair
            if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
            {
    
                return new KeyValuePair<TKey, TValue>(
                                                        (TKey)type.GetProperty("Key").GetValue(obj, null), 
                                                        (TValue)type.GetProperty("Value").GetValue(obj, null)
                                                     );
    
            }
            // if obj type does not match KeyValuePair throw exception
            throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");   
     }
    

    and usage would be like:

    KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();
    
    0 讨论(0)
  • 2020-12-13 18:11

    As I understand it, you're not sure what the keys and values are, but you want to convert them into strings?

    Maybe this can work:

    public static void MyMethod(object obj)
    {
      var iDict = obj as IDictionary;
      if (iDict != null)
      {
        var dictStrStr = iDict.Cast<DictionaryEntry>()
          .ToDictionary(de => de.Key.ToString(), de => de.Value.ToString());
    
        // use your dictStrStr        
      }
      else
      {
        // My object is not an IDictionary
      }
    }
    
    0 讨论(0)
  • 2020-12-13 18:14

    This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):

        private static Dictionary<TKey, TValue> ObjectToDictionary<TKey, TValue>(object source)
        {
            Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();
    
            TKey[] keys = { };
            TValue[] values = { };
    
            bool outLoopingKeys = false, outLoopingValues = false;
    
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value is Dictionary<TKey, TValue>.KeyCollection)
                {
                    keys = ((Dictionary<TKey, TValue>.KeyCollection)value).ToArray();
                    outLoopingKeys = true;
                }
                if (value is Dictionary<TKey, TValue>.ValueCollection)
                {
                    values = ((Dictionary<TKey, TValue>.ValueCollection)value).ToArray();
                    outLoopingValues = true;
                }
                if(outLoopingKeys & outLoopingValues)
                {
                    break;
                }
            }
    
            for (int i = 0; i < keys.Length; i++)
            {
                result.Add(keys[i], values[i]);
            }
    
            return result;
        }
    
    0 讨论(0)
  • 2020-12-13 18:15

    The above answers are all cool. I found it easy to json serialize the object and deserialize as a dictionary.

    var json = JsonConvert.SerializeObject(obj);
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    

    I don't know how performance is effected but this is much easier to read. You could also wrap it inside a function.

    public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
    {       
        var json = JsonConvert.SerializeObject(obj);
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);   
        return dictionary;
    }
    

    Use like so:

    var obj = new { foo = 12345, boo = true };
    var dictionary = ToDictionary<string>(obj);
    
    0 讨论(0)
  • 2020-12-13 18:15

    Assuming key can only be a string but value can be anything try this

    public static Dictionary<TKey, TValue> MyMethod<TKey, TValue>(object obj)
    {
        if (obj is Dictionary<TKey, TValue> stringDictionary)
        {
            return stringDictionary;
        }
    
        if (obj is IDictionary baseDictionary)
        {
            var dictionary = new Dictionary<TKey, TValue>();
            foreach (DictionaryEntry keyValue in baseDictionary)
            {
                if (!(keyValue.Value is TValue))
                {
                    // value is not TKey. perhaps throw an exception
                    return null;
                }
                if (!(keyValue.Key is TKey))
                {
                    // value is not TValue. perhaps throw an exception
                    return null;
                }
    
                dictionary.Add((TKey)keyValue.Key, (TValue)keyValue.Value);
            }
            return dictionary;
        }
        // object is not a dictionary. perhaps throw an exception
        return null;
    }
    
    0 讨论(0)
  • 2020-12-13 18:23

    this should work:

    for numbers, strings, date, etc.:

        public static void MyMethod(object obj)
        {
            if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
            {
                IDictionary idict = (IDictionary)obj;
    
                Dictionary<string, string> newDict = new Dictionary<string, string>();
                foreach (object key in idict.Keys)
                {
                    newDict.Add(key.ToString(), idict[key].ToString());
                }
            }
            else
            {
                // My object is not a dictionary
            }
        }
    

    if your dictionary also contains some other objects:

        public static void MyMethod(object obj)
        {
            if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
            {
                IDictionary idict = (IDictionary)obj;
                Dictionary<string, string> newDict = new Dictionary<string, string>();
    
                foreach (object key in idict.Keys)
                {
                    newDict.Add(objToString(key), objToString(idict[key]));
                }
            }
            else
            {
                // My object is not a dictionary
            }
        }
    
        private static string objToString(object obj)
        {
            string str = "";
            if (obj.GetType().FullName == "System.String")
            {
                str = (string)obj;
            }
            else if (obj.GetType().FullName == "test.Testclass")
            {
                TestClass c = (TestClass)obj;
                str = c.Info;
            }
            return str;
        }
    
    0 讨论(0)
提交回复
热议问题