字符串,对象>如何解释&LT转换;到字典<字符串,字符串>在c# [英] How to convert Dictionary<string, object> to Dictionary<string, string> in c#

查看:366
本文介绍了字符串,对象>如何解释&LT转换;到字典<字符串,字符串>在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码在C#

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



我想 dObject 转换为字典<字符串,字符串> 。我怎样才能做到这一点。

I want to convert dObject to Dictionary<string, string>. How can I do this?

推荐答案

使用的ToDictionary方法:

Use the ToDictionary method:

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



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

Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.

如果你的字典可以包含空值,你应该执行的ToString前添加一个空检查:

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



这部作品的原因是,词典<字符串对象> code>实际上是一个的IEnumerable<是。通过枚举上面的代码示例循环并建立使用ToDictionary方法一个新的字典。

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.

编辑:

在NET 2.0,你不能使用ToDictionary方法,但你可以使用老式的foreach达到相同的:

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:

如果您是在NET 2.0,您可以在字典中的以下应该是安全有NULL值:

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

这篇关于字符串,对象&gt;如何解释&LT转换;到字典&LT;字符串,字符串&GT;在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆