如何在C#</string,> </string,>中将Dictionary <string,object =“”>转换为Dictionary <string,string =“”>

时间:2011-02-09 08:18:25

标签: c# c#-2.0

我在C#中有以下代码

Dictionary<string, object> dObject = new Dictionary<string, object>();

我想将dObject转换为Dictionary<string, string>。我怎么能这样做?

6 个答案:

答案 0 :(得分:93)

使用ToDictionary方法:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());

在这里,您可以重用原始字典中的键,并使用ToString方法将值转换为字符串。

如果您的字典可以包含空值,则应在执行ToString之前添加空检查:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());

这有效的原因是Dictionary<string, object>实际上是IEnumerable<KeyValuePair<string,object>>。上面的代码示例遍历可枚举,并使用ToDictionary方法构建新的字典。

修改

在.Net 2.0中,你不能使用ToDictionary方法,但你可以使用一个好的老式foreach来实现同样的目标:

Dictionary<string, string> sd = new Dictionary<string, string>(); 
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
  sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}

<强> EDIT2:

如果您使用的是.Net 2.0,并且字典中可以包含空值,则以下内容应该是安全的:

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());
}

答案 1 :(得分:8)

.NET 3.5:

Dictionary<string, string> result = dObject.ToDictionary(kvp => kvp.Key, kvp => Convert.ToString(kvp.Value));

.NET 2.0:

Dictionary<string, string> result = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> kvp in dObject) result.Add(kvp.Key, Convert.ToString(kvp.Value));

答案 2 :(得分:4)

因为您使用的是.net 2.0:

Dictionary<string, string> dString = new Dictionary<string, string>();

foreach (KeyValuePair<string, object> item in dObject)
{
    dString.Add(item.Key, item.Value.ToString());
    //here item.Value.ToString() is an example
    //you should convert your item to string according to the requirement
}

答案 3 :(得分:2)

怎么样:

Dictionary<string, string> newDictionary = dObject.ToDictionary(k => k.Key, k => (string) k.Value);

答案 4 :(得分:1)

在.Net 2.0中,你最好的朋友可能是 foreach 循环:

Dictionary<string, object> dObject = new Dictionary<string, object>();
Dictionary<string, string> newObjects = new Dictionary<string, string>();

foreach (KeyValuePair<string, object> keyValuePair in dObject)
{
    newObjects.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}

答案 5 :(得分:0)

Dictionary<string, string> dString = dObject.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());

这只是想法。您可以插入任何验证。