2010-02-02 10 views
10

Sto utilizzando un'API che restituisce una raccolta di valori-chiave come Dictionary<string, string>. Devo convertirlo in un Dictionary<string, object>. Ho la sensazione che ci dovrebbe essere un modo per fare questa conversione/mappatura senza "manualmente" il ciclo attraverso ogni coppia chiave-valore, ma Googling o il riferimento all'oggetto C# non ha prodotto immediatamente una soluzione.Qual è il modo più semplice per convertire un dizionario <stringa, stringa> in un dizionario <stringa, oggetto>?

risposta

22

Provate il seguente

var newMap = oldMap.ToDictionary(pair => pair.Key, pair=>(object)pair.Value); 
+0

+1, ma vale la pena notare che questo non è più "snello" del modo in cui l'OP vuole evitare, ma lo nasconde dietro una sintassi piuttosto brillante. –

+0

@Rex, true, ma evita il loop manuale come richiesto dall'OP. – JaredPar

+0

"Lean" può essere allungato per significare cose diverse. Nel mio caso stavo solo cercando una soluzione rapida per salvare la giornata. Grazie per questa risposta. –

0

È possibile utilizzare questo metodo di estensione:

public static class ObjectExtensions 
{ 
    public static object GetPropertyValue(this object obj, string property) 
    { 
     return TypeDescriptor.GetProperties(obj)[property].GetValue(obj); 
    } 

    public static IDictionary<string, object> ToDictionary(this object obj) 
    { 
     IDictionary<string, object> result = new Dictionary<string, object>(); 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj); 
     foreach (PropertyDescriptor property in properties) 
     { 
      result.Add(property.Name, property.GetValue(obj)); 
     } 
     return result; 
    } 
} 

Si usa piace:

new Dictionary<string, string>().ToDictionary(); 
3

No looping, mappa un Dictionary{T, U} a Dictionary{T, object} in tempo costante:

class DictionaryWrapper<T, U> : IDictionary<T, object> 
{ 
    readonly Dictionary<T, U> inner; 
    public DictionaryWrapper(Dictionary<T, U> wrapped) 
    { 
     this.inner = wrapped; 
    } 

    #region IDictionary<T,object> Members 

    public void Add(T key, object value) { inner.Add(key, (U)value); } 
    public bool ContainsKey(T key) { return inner.ContainsKey(key); } 
    public ICollection<T> Keys { get { return inner.Keys; } } 
    public bool Remove(T key) { return inner.Remove(key); } 

    public bool TryGetValue(T key, out object value) 
    { 
     U temp; 
     bool res = inner.TryGetValue(key, out temp); 
     value = temp; 
     return res; 
    } 

    public ICollection<object> Values { get { return inner.Values.Select(x => (object)x).ToArray(); } } 

    public object this[T key] 
    { 
     get { return inner[key]; } 
     set { inner[key] = (U)value; } 
    } 

    #endregion 

    #region ICollection<KeyValuePair<T,object>> Members 

    public void Add(KeyValuePair<T, object> item) { inner.Add(item.Key, (U)item.Value); } 
    public void Clear() { inner.Clear(); } 
    public bool Contains(KeyValuePair<T, object> item) { return inner.Contains(new KeyValuePair<T, U>(item.Key, (U)item.Value)); } 
    public void CopyTo(KeyValuePair<T, object>[] array, int arrayIndex) { throw new NotImplementedException(); } 
    public int Count { get { return inner.Count; } } 
    public bool IsReadOnly { get { return false; } } 
    public bool Remove(KeyValuePair<T, object> item) { return inner.Remove(item.Key); } 

    #endregion 

    #region IEnumerable<KeyValuePair<T,object>> Members 

    public IEnumerator<KeyValuePair<T, object>> GetEnumerator() 
    { 
     foreach (var item in inner) 
     { 
      yield return new KeyValuePair<T, object>(item.Key, item.Value); 
     } 
    } 

    #endregion 

    #region IEnumerable Members 

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
    { 
     foreach (var item in inner) 
     { 
      yield return new KeyValuePair<T, object>(item.Key, item.Value); 
     } 
    } 

    #endregion 
} 

Con pochi params più generici, si può generalizzare questa classe ulteriormente, in modo che mappa un Dictionary{A, B} ad un Dictionary{C, D}.

Problemi correlati