如何在C#中将对象转换为Dictionary ?

如何在C中将动态对象转换为Dictionary #我该怎么办?

 public static void MyMethod(object obj) { if (typeof(IDictionary).IsAssignableFrom(obj.GetType())) { // My object is a dictionary, casting the object: // (Dictionary) obj; // causes error ... } else { // My object is not a dictionary } } 

  public static KeyValuePair Cast(this KeyValuePair kvp) { return new KeyValuePair(kvp.Key, kvp.Value); } public static KeyValuePair CastFrom(Object obj) { return (KeyValuePair) obj; } public static KeyValuePair CastFrom(Object obj) { var type = obj.GetType(); if (type.IsGenericType) { if (type == typeof (KeyValuePair<,>)) { var key = type.GetProperty("Key"); var value = type.GetProperty("Value"); var keyObj = key.GetValue(obj, null); var valueObj = value.GetValue(obj, null); return new KeyValuePair(keyObj, valueObj); } } throw new ArgumentException(" ### -> public static KeyValuePair CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>"); } 

来自OP:

而不是转换我的整个词典,我决定保持我的obj动态一直。 当我使用foreach访问我的Dictionary的键和值时,我使用foreach(obj.Keys中的动态键)并简单地将键和值转换为字符串。

我用这个帮手:

 public static class ObjectToDictionaryHelper { public static IDictionary ToDictionary(this object source) { return source.ToDictionary(); } public static IDictionary ToDictionary(this object source) { if (source == null) ThrowExceptionWhenSourceArgumentIsNull(); var dictionary = new Dictionary(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source)) AddPropertyToDictionary(property, source, dictionary); return dictionary; } private static void AddPropertyToDictionary(PropertyDescriptor property, object source, Dictionary dictionary) { object value = property.GetValue(source); if (IsOfType(value)) dictionary.Add(property.Name, (T)value); } private static bool IsOfType(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."); } } 

用法只是在一个对象上调用.ToDictionary()

希望能帮助到你。

以上答案都很酷。 我发现json序列化对象很容易,反序列化为字典。

 var json = JsonConvert.SerializeObject(obj); var dictionary = JsonConvert.DeserializeObject>(json); 

我不知道性能是如何影响的,但这更容易阅读。 你也可以将它包装在一个函数中。

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

使用如下:

 var obj = new { foo = 12345, boo = true }; var dictionary = ToDictionary(obj); 

这应该工作:

数字,字符串,日期等:

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

如果你的字典还包含一些其他对象:

  public static void MyMethod(object obj) { if (typeof(IDictionary).IsAssignableFrom(obj.GetType())) { IDictionary idict = (IDictionary)obj; Dictionary newDict = new Dictionary(); 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; } 

假设键只能是一个字符串,但值可以是任何尝试

 public static Dictionary MyMethod(object obj) { var stringDictionary = obj as Dictionary; if (stringDictionary!= null) { return stringDictionary; } var baseDictionary = obj as IDictionary; if (baseDictionary != null) { var dictionary = new Dictionary(); 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; } 
  public static void MyMethod(object obj){ Dictionary dicEditdata = data as Dictionary; string abc=dicEditdata["id"].ToString();} 

假设—如果你在调试时把光标放在对象(obj)上,如果你得到一个值为{['id':'ID1003']}的对象,你可以使用该值作为

 string abc=dicEditdata["id"].ToString(); 

您可以创建一个通用扩展方法,然后在对象上使用它,如:

 public static class Extensions { public static KeyValuePair ToKeyValuePair(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)) { return new KeyValuePair( (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}>"); } 

用法如下:

 KeyValuePair kvp = obj.ToKeyValuePair(); 

我用这个简单的方法:

 public Dictionary objToDict(XYZ.ObjectCollection objs) { var dict = new Dictionary(); foreach (KeyValuePair each in objs){ dict.Add(each.Key, each.Value); } return dict; } 

此代码可安全地将Object转换为Dictionary(具有源对象来自Dictionary的前提):

  private static Dictionary ObjectToDictionary(object source) { Dictionary result = new Dictionary(); 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.KeyCollection) { keys = ((Dictionary.KeyCollection)value).ToArray(); outLoopingKeys = true; } if (value is Dictionary.ValueCollection) { values = ((Dictionary.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; } 

据我所知,你不确定键和值是什么,但你想将它们转换成字符串?

也许这可行:

 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 } } 
 object parsedData = se.Deserialize(reader); System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable; 

然后就可以枚举了!

简单方法:

 public IDictionary toDictionary(Object objAttached) { var dicCurrent = new Dictionary(); foreach (DictionaryEntry dicData in (objAttached as IDictionary)) { dicCurrent.Add((T)dicData.Key, (V)dicData.Value); } return dicCurrent; }