I have below code in C#
Dictionary<string, object> dObject = new Dictionary<string, object>();
I want to convert dObject to Dictionary<string, string>. How can I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the ToDictionary method:
Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.
If your dictionary can contain null values you should add a null check before performing the ToString:
The reason this works is that the
Dictionary<string, object>is actually anIEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.Edit:
In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:
Edit2:
If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe: