2012-08-29 35 views
68

¿Cómo puedo obtener el valor del diccionario por la clave en la funciónobtener el valor por el diccionario clave

mi código de función es esto (y el comando lo que intento, pero no funcionó):

static void XML_Array(Dictionary<string, string> Data_Array) 
{ 
    String xmlfile = Data_Array.TryGetValue("XML_File", out value); 
} 

mi código del botón es este

private void button2_Click(object sender, EventArgs e) 
{ 
    Dictionary<string, string> Data_Array = new Dictionary<string, string>(); 
    Data_Array.Add("XML_File", "Settings.xml"); 

    XML_Array(Data_Array); 
} 

quiero algo como esto:
en XML_Array función sea
cadena xmlfile = Settings.xml

+1

no se olvide de marcar una respuesta como una solución aceptable para su problema, si le ayuda. esta 'pista' también está relacionada con sus preguntas anteriores. http://meta.stackexchange.com/a/5235 – varg

+4

... y no uses guiones bajos en tus nombres de variables, ¡es tan feo! – Guillaume

Respuesta

97

Es tan simple como esto:

String xmlfile = Data_Array["XML_File"]; 

Tenga en cuenta que si el diccionario no tiene una clave que es igual "XML_File", ese código será una excepción. Si desea comprobar en primer lugar, se puede utilizar TryGetValue así:

string xmlfile; 
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) { 
    // the key isn't in the dictionary. 
    return; // or whatever you want to do 
} 
// xmlfile is now equal to the value 
+2

hombre genial gracias! esto era lo que estaba buscando –

20

no es así como los TryGetValue obras. Devuelve true o false según se encuentre o no la clave, y establece su parámetro out en el valor correspondiente si la clave está allí.

Si desea comprobar si la clave está ahí o no, y hacer algo cuando falta, se necesita algo como esto:

bool hasValue = Data_Array.TryGetValue("XML_File", out value); 
if (hasValue) { 
    xmlfile = value; 
} else { 
    // do something when the value is not there 
} 
4
static void XML_Array(Dictionary<string, string> Data_Array) 
{ 
    String value; 
    if(Data_Array.TryGetValue("XML_File", out value)) 
    { 
    ... Do something here with value ... 
    } 
} 
2
static String findFirstKeyByValue(Dictionary<string, string> Data_Array, String value) 
{ 
    if (Data_Array.ContainsValue(value)) 
    { 
     foreach (String key in Data_Array.Keys) 
     { 
      if (Data_Array[key].Equals(value)) 
       return key; 
     } 
    } 
    return null; 
} 
2
  private void button2_Click(object sender, EventArgs e) 
      { 
       Dictionary<string, string> Data_Array = new Dictionary<string, string>(); 
       Data_Array.Add("XML_File", "Settings.xml"); 

       XML_Array(Data_Array); 
      } 
      static void XML_Array(Dictionary<string, string> Data_Array) 
      { 
       String xmlfile = Data_Array["XML_File"]; 
      } 
0

Puedo usar un método similar a dasblinkenlight's en una función para devolver un valor de clave individual de una Cookie que contiene una matriz JSON cargada en un diccionario de la siguiente manera:

/// <summary> 
    /// Gets a single key Value from a Json filled cookie with 'cookiename','key' 
    /// </summary> 
    public static string GetSpecialCookieKeyVal(string _CookieName, string _key) 
    { 
     //CALL COOKIE VALUES INTO DICTIONARY 
     Dictionary<string, string> dictCookie = 
     JsonConvert.DeserializeObject<Dictionary<string, string>> 
     (MyCookinator.Get(_CookieName)); 

     string value; 
     if (dictCookie.TryGetValue(_key, out value)) 
     { 
      return value; 
     } 
     else 
     { 
      return "0"; 
     } 

    } 

Donde "MyCookinator.Get()" es otra función de Cookie simple que obtiene un valor global de la cookie http.

16

¿Por qué no usar el nombre clave de diccionario, C# tiene esto:

Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("UserID", "test"); 
string userIDFromDictionaryByKey = dict["UserID"]; 

Si nos fijamos en la sugerencia de punta:

enter image description here

0

Aquí es ejemplo que utilizo en mi fuente código. Obtengo clave y valor del Diccionario del elemento 0 al número de elementos en mi Diccionario. A continuación, lleno mi string [] matriz que envío como un parámetro después en mi función que sólo aceptan cadena params []

Dictionary<string, decimal> listKomPop = addElements(); 
    int xpopCount = listKomPop.Count; 
    if (xpopCount > 0) 
    { 
     string[] xpostoci = new string[xpopCount]; 
     for (int i = 0; i < xpopCount; i++) 
     { 
      /* here you have key and value element */ 
      string key = listKomPop.Keys.ElementAt(i); 
      decimal value = listKomPop[key]; 

      xpostoci[i] = value.ToString(); 
     } 
    ... 

la esperanza que esto ayudará a usted y los demás. Esta solución también funciona con SortedDictionary.

Saludos cordiales,

Ozren Sirola

0
Dictionary<String,String> d = new Dictionary<String,String>(); 
     d.Add("1","Mahadev"); 
     d.Add("2","Mahesh"); 
     Console.WriteLine(d["1"]);// it will print Value of key '1' 
Cuestiones relacionadas