Use the ToDictionary method:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());
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:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());
The reason this works is that the Dictionary<string, object>
is actually an IEnumerable<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:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}
Edit2:
If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…