How to convert object to Dictionary in C#?

前端 未结 15 1783
隐瞒了意图╮
隐瞒了意图╮ 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: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()
          .ToDictionary(de => de.Key.ToString(), de => de.Value.ToString());
    
        // use your dictStrStr        
      }
      else
      {
        // My object is not an IDictionary
      }
    }
    

提交回复
热议问题