This method is often used and effective. Trygetvalue:Obtains the value associated with the specified key.
For example, if we read an XML file and write it to the dictionary for storage:
Private Static dictionary <string, string> sqlkeyvalues = NULL; /// <summary> // Required User field and alias // </Summary> internal static void inituserfields (xmldocument XML) {loadxml (XML); xmlnode fields = xml. selectsinglenode ("/configs/users/fields"); userfields = new dictionary <string, string> (); If (fields. childnodes. count> 0) {foreach (xmlnode N in fields. childnodes) {If (N. nodetype! = Xmlnodetype. comment & N. name. tolower () = "item") {xmlattribute fieldname = n. attributes ["name"]; userfields. add (fieldname. value, N. innerxml );}}}}
We can obtain the value of the corresponding key through the following aspects:
public static string GetUserField(string fieldName) { string finfo = ""; UserFields.TryGetValue(fieldName, out finfo); return finfo; }
(Bool) (userfields. trygetvalue (fieldname, out finfo) can be converted to the boo type, which is convenient to avoid"The specified keyword is not in the dictionary.. You can learn more through the following tests:
Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("aaa", "123"); dic.Add("bbb", "456"); dic.Add("ccc", "789"); dic.Add("ddd", "321"); string outStr = "999"; dic.TryGetValue("ttt", out outStr); Response.Write(outStr + "<br />"); dic.TryGetValue("bbb", out outStr); Response.Write(outStr + "<br />"); //Response.Write(dic["ttt"] + "<br />");