64

動的オブジェクトをC#でに変換するにはどうすればDictionary<TKey, TValue>よいですか?

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

18 に答える 18

25
    public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)
    {
        return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
    }

    public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
    {
        return (KeyValuePair<T, V>) obj;
    }

    public static KeyValuePair<object , object > 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<object, object>(keyObj, valueObj);
            }
        }
        throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
    }

OPから:

辞書全体を変換する代わりに、objを常に動的に保つことにしました。後でforeachを使用して辞書のキーと値にアクセスするときは、foreach(obj.Keysの動的キー)を使用して、キーと値を単純に文字列に変換します。

于 2012-11-28T10:21:56.380 に答える
7

これはうまくいくはずです:

数値、文字列、日付など:

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

辞書に他のオブジェクトも含まれている場合:

    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;
    }
于 2012-07-20T10:06:09.817 に答える
3

キーは文字列のみであると仮定しますが、値は何でもかまいませんこれを試してください

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;
}
于 2012-07-20T11:45:16.347 に答える
3
   public static void MyMethod(object obj){
   Dictionary<string, string> dicEditdata = data as Dictionary<string, string>;
   string abc=dicEditdata["id"].ToString();} 

仮定---デバッグ中にオブジェクト(obj)の上にカーソルを置き、値を持つオブジェクトを取得すると、値{['id':'ID1003']} を次のように使用できます

string abc=dicEditdata["id"].ToString(); 
于 2014-08-01T12:02:27.077 に答える
0

汎用拡張メソッドを作成して、次のようにオブジェクトで使用できます。

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

使用法は次のようになります。

KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();
于 2016-11-28T11:06:35.677 に答える
0

このように、オブジェクト配列から Dictionary<string, object> リストへの変換

object[] a = new object[2];
var x = a.Select(f => (Dictionary<string, object>)f).ToList();

このように、単一のオブジェクトから Dictionary<string, object> への変換

object a = new object;
var x = (Dictionary<string, object>)a;
于 2022-02-06T16:59:25.667 に答える
-1

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
  }
}
于 2012-07-20T10:10:41.317 に答える
-1
object parsedData = se.Deserialize(reader);
System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable;

その後、それを列挙することができます!

于 2014-07-18T17:39:09.023 に答える
-2

簡単な方法:

public IDictionary<T, V> toDictionary<T, V>(Object objAttached)
{
    var dicCurrent = new Dictionary<T, V>();
    foreach (DictionaryEntry dicData in (objAttached as IDictionary))
    {
        dicCurrent.Add((T)dicData.Key, (V)dicData.Value);
    }
    return dicCurrent;
}
于 2016-09-15T03:56:30.687 に答える